Skip to content

Web APIs with Flask: From the App to a JSON API

From Hello World to a JSON API: how routing, request handling and jsonify work together in Flask 1.1 – and why SSR and APIs are the same mechanism.

≈ 10 min readSoftwarePythonBackend

Three terms are enough to describe everything Flask does: route, request, response. A decorator binds a URL path to a Python function, the request object describes the incoming request, and the function’s return value becomes the response. Templates, blueprints, JSON – everything else hangs off these three points.

That makes Flask a good starting point when a Python script is supposed to become an interface another program can talk to over HTTP. It’s a micro-framework: routing, request object and template engine are included, almost everything else is left open. There’s hardly any magic you’d first have to take apart to understand what actually happens between the HTTP request and your own function. Throughout, this text refers to Flask 1.1 – the stable series at the time of writing (1.1.2 came out in April 2020). If you’ve worked with Python objects, decorators and dictionaries before, you’ll find your way quickly.

Editorial note (July 2026): In today’s Flask 3.1, request.json calls get_json() internally and responds with 415 by default if the Content-Type isn’t suitable. Only request.get_json(silent=True) returns None in that case. This change affects error handling, not the routing model of this article.

Hello World, and what’s behind it#

The smallest meaningful Flask server fits into six lines. You can read the entire model from it.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run(debug=True, port=8080)

Flask(__name__) creates the application. Flask later uses the module name as a starting point, for example to find templates and static files relative to the project. The decorator @app.route('/') links a URL path to a function. When the server is called at /, Flask calls hello_world() and sends the return value back as the response. app.run() starts the built-in development server.

The central idea: a function that returns a string becomes an HTTP response with Content-Type: text/html. Flask takes care of the entire translation between HTTP and the Python function for me. And this translation is more flexible than the first impression suggests. A view may return not only a string but also a tuple of body and status code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!', 202

Here the client gets the same text, but with status 202 instead of the default 200. The tuple can even have three elements – body, status and a dictionary with additional headers. These return conventions are the core of Flask, and they explain why the same route sometimes behaves as an HTML page and sometimes as a JSON API.

Routing, request, response#

Before we get to the actual API, the three terms deserve a closer look, because they come up again and again:

  • Route: The decorator @app.route(pfad, methods=[...]) binds a URL path to a function. Path parameters like <int:item_id> pass parts of the URL directly to the function, and methods defines which HTTP verbs the route serves.
  • Request: The imported request object describes the incoming request – request.args reads the query string, request.form the form fields, request.json the JSON body, request.method the verb used.
  • Response: The function’s return value. A string becomes HTML, jsonify(...) becomes JSON, a tuple (rumpf, status) controls the status code.

These three axes are enough to build a surprising amount. A path with a parameter looks something like this:

@app.route('/user/<username>')
def profile(username):
    return f'Profile page of {username}'

The placeholder <username> is passed to the function as an argument. If you need a numeric value, the converter <int:item_id> requires an integer and delivers it already as an int – if the path doesn’t match this pattern, Flask responds with 404 on its own, before my function even runs.

The request lifecycle can be summarized in a simple diagram. Between the incoming request and the finished response there are only a few clearly named steps.

graph LR
    A[HTTP Request] --> B["@app.route<br/>Matching"]
    B --> C[View Handler]
    C --> D["jsonify()"]
    D --> E[JSON Response]

The request arrives, Flask looks for the matching route, calls the associated function, which builds a response with jsonify, and that goes back to the client. None of these steps is hidden – you can put a print anywhere and watch.

From page to interface#

Now to the actual goal: a small, REST-style interface. For this I build a single path that serves two verbs – a GET returns the list of all entries, a POST creates a new one. That one URL can serve several methods is exactly the point where REST thinking becomes visible: the resource is the same, only the action on it differs.

from flask import Flask, request, jsonify

app = Flask(__name__)
items = []  # demo-only in-memory store

@app.route('/items', methods=['GET', 'POST'])
def items_collection():
    if request.method == 'POST':
        payload = request.get_json()
        item = {'id': len(items) + 1, 'name': payload['name']}
        items.append(item)
        return jsonify(item), 201
    return jsonify(items)  # GET

@app.route('/items/<int:item_id>')
def item_detail(item_id):
    match = next((i for i in items if i['id'] == item_id), None)
    return (jsonify(match), 200) if match else ('Not found', 404)

A few things here are deliberate. For POST, I read the JSON body with request.get_json() and respond with status 201, the code for “created.” For GET, I return the entire list. And the second route shows the path parameter in action: /items/3 looks up the entry with this ID and returns either it or a 404 response.

jsonify is more than a prettier json.dumps. It serializes the dictionary or list, sets the Content-Type correctly to application/json and builds a finished response object. The handmade way – turning json.dumps(...) into a string and setting the header manually – works, but it’s more error-prone and duplicates exactly the work Flask does cleanly anyway.

The historical twist: returning a dict directly#

A note is worth making here, because it causes confusion in older examples. Since Flask 1.1, a view may return a dict directly – Flask then automatically calls jsonify() on it internally:

@app.route('/status')
def status():
    return {'ok': True, 'items': len(items)}  # Flask >= 1.1 -> JSON

That’s convenient, but it’s a relatively recent convenience. In Flask 1.0 and earlier, exactly this line was an error: a dictionary wasn’t a valid return type, and you got a TypeError. If you wanted to deliver JSON back then, you had to write return jsonify({...}) explicitly. Tutorials and Stack Overflow answers show both variants side by side without stating the version – which makes it easy to mix up version and behavior. As long as I’m not sure which Flask version is running, I write jsonify explicitly. It works in every version and makes the intent clear.

SSR and APIs are the same mechanism#

Server-side rendering (SSR) and a JSON API are often seen as two different worlds. In Flask they aren’t: the same routing mechanism, the same function, just a different return type. Instead of jsonify, I use render_template, which fills an HTML file from the templates/ folder with Jinja2.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', items=items)

@app.route('/forms', methods=['POST'])
def forms():
    return 'You said: ' + request.form['text']

The corresponding template is ordinary HTML with placeholders. The context passed in – here items – is available in the template as a variable:

<form action="/forms" method="POST">
  <input name="text">
  <input type="submit" value="Submit">
</form>

<ul>
  {% for item in items %}
    <li>{{ item.name }}</li>
  {% endfor %}
</ul>

The difference between the API and the rendered page is purely the representation: once JSON for machines, once HTML for the browser. The framework underneath stays the same. As a diagram, the branching is quickly told.

graph LR
    A[View Handler] --> B{Representation?}
    B -->|render_template| C[HTML]
    B -->|jsonify| D[JSON]

With that, “API framework” and “web framework” dissolve as separate categories. It’s a decision per route, not an architectural break.

Structure with blueprints#

As soon as more than a handful of routes come together, the one big app.py gets cluttered. Flask offers blueprints for this – a way to group routes by topic and attach them to the app with a shared prefix.

from flask import Blueprint, jsonify

api = Blueprint('api', __name__, url_prefix='/api')

@api.route('/items')
def list_items():
    return jsonify(items)

# in the main app:
# app.register_blueprint(api)

All routes of this blueprint then live under /api – so the route above is reachable at /api/items. Important to understand: a blueprint is purely a structural tool. It doesn’t change anything about runtime behavior and brings no magic of its own; it only helps cut the code into understandable units. I like to use it to separate the JSON API from the rendered pages – two blueprints, one project.

Three pitfalls#

Finally, the places where things regularly get stuck in practice. None of these points is a bug in Flask – they’re peculiarities you need to know.

The first concerns request.json. In the Flask 1.1 used here, the value was simply None without Content-Type: application/json, and a direct access like payload['name'] ran into an error. Current Flask versions respond to this access with 415 by default. If you deliberately want to handle it yourself, use request.get_json(silent=True) and check for a possible None.

@app.route('/echo', methods=['POST'])
def echo():
    data = request.get_json(silent=True)
    if not data:
        return jsonify({'error': 'expected JSON body'}), 400
    return jsonify(data)

The second is debug=True. In the development server, debug mode is handy – it reloads on changes and shows an interactive traceback on errors. But exactly this interactive traceback is an executable console in the browser. In a publicly reachable environment, that’s an open door for executing arbitrary code. debug=True belongs exclusively in local development. And app.run() itself is only the development server anyway – for production, you put a WSGI server like gunicorn or uWSGI in front of it.

The third concerns global state. My items = [] list is a demo shortcut and not a database. It lives in the process’s memory, is lost on every restart and behaves unreliably as soon as several workers run in parallel – then each worker sees its own list. For an example like this, that’s perfectly fine; for real data you need persistence, such as a database behind the route.

Conclusion#

The path from a Python script to a web interface is shorter with Flask than many expect, and – more importantly – it’s easy to follow. A function is bound to a path through a decorator, the request object describes the request, the return value becomes the response. Whether that becomes an HTML page via render_template or a JSON API via jsonify is a decision per route, not a change of system. Blueprints give the whole thing structure as it grows, without introducing new concepts.

More important to me than the list of features is that you can say at any time what happens between the HTTP request and your own function. Flask keeps this chain visible. Once you’ve walked through it, you’ll also read more comfortable frameworks more calmly – underneath, they all have the same model of route, request and response.

Further reading#

Revised and translated from German with the help of AI.