Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 72 ยท REST APIs

Building JSON APIs

Build a JSON API with Flask. Learn jsonify, request.get_json, the right status codes, a consistent error format and simple content negotiation.

So far your views have mostly returned HTML for a browser. A JSON API returns data instead: a mobile app, a JavaScript front end or another server calls your URLs, sends JSON in, and gets JSON back. There are no templates and no redirects. What matters is that the data is shaped well, the status codes are honest, and errors look the same everywhere.

Flask needs no extra package for this. In this lesson you will return JSON with jsonify, read JSON from the request body with request.get_json, choose status codes, design one error format for the whole API, and answer differently depending on what the client asks for (content negotiation).

The shape of a JSON API

sequenceDiagram
    participant C as Client
    participant F as Flask view
    C->>F: POST /api/notes<br/>Content-Type: application/json<br/>{"text": "buy milk"}
    F->>F: request.get_json()
    F->>F: validate, save
    F-->>C: 201 Created<br/>Location: /api/notes/1<br/>{"id": 1, "text": "buy milk"}

The client says it is sending JSON with a header; the server answers with a status code, headers and a JSON body.

Returning JSON

You met this in Responses, Status Codes and Headers: a view that returns a dict or a list is converted to a JSON response automatically. jsonify() does the same job explicitly and accepts keyword arguments. Both set Content-Type: application/json.

Python Returning JSON from views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

True and False become true and false, and None becomes null. Python objects that JSON does not know (a datetime, a Decimal, a set) need care: Flask's JSON provider handles datetime, date, UUID, Decimal and dataclasses, but anything else raises a TypeError. When in doubt, convert to basic types yourself, as the next lessons do with schemas.

jsonify or json.dumps?

You can build a JSON string yourself with json.dumps and return it, but then you must also set the Content-Type: application/json header, or clients will treat the body as HTML. jsonify (and returning a dict) does both steps, and it knows more types. Plain json.dumps fails on a Decimal, a date or a UUID. It also escapes non-ASCII letters by default and sorts nothing, while Flask's provider has its own settings.

Python jsonify compared with json.dumps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that jsonify turned the date into an HTTP-style string (Tue, 04 Mar 2025 00:00:00 GMT) and the Decimal into a string "9.50", so no precision is lost. If you want ISO dates, convert them yourself (added.isoformat()) or replace the provider (app.json = MyProvider(app)).

The options you will actually use:

Setting json.dumps argument Flask (app.json.*)
Sorted keys sort_keys=True sort_keys (default True)
Keep รฉ as a letter ensure_ascii=False ensure_ascii (default True)
Compact output separators=(",", ":") compact (default: compact unless debugging)
Custom types default=function default or a provider subclass

Another difference: json.dumps(..., indent=2) is for humans reading logs. Do not pretty-print API responses in production, since whitespace only makes them bigger.

Reading JSON from the request

A client sends JSON in the body and says so with Content-Type: application/json. In the view you read it with request.get_json():

  • It returns the parsed Python value (usually a dict).
  • If the content type is not JSON, Flask answers 415 Unsupported Media Type.
  • If the body is not valid JSON, Flask answers 400 Bad Request.
  • get_json(silent=True) returns None instead of raising, which lets you produce your own error.
Python Create a resource with POST

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the third and fourth requests: the bad content type and the broken JSON are rejected by get_json(silent=True) returning None, so our own check produces the 400. Without silent=True, Flask would raise its own HTML error response, which is wrong for an API (more on that below).

The test client's json= argument serializes a Python value and sets the right header, which is why the first request needs no manual Content-Type.

Status codes that tell the truth

Clients often branch on the status code before they look at the body, so use the standard ones:

Situation Code
Data returned 200 OK
Resource created (POST) 201 Created, with a Location header
Success, nothing to return (DELETE) 204 No Content
Malformed request, missing field 400 Bad Request
Syntax is fine but values are invalid 422 Unprocessable Content
Not logged in / wrong token 401 Unauthorized
Logged in but not allowed 403 Forbidden
No such resource 404 Not Found
Wrong HTTP method for this URL 405 Method Not Allowed
Wrong Content-Type 415 Unsupported Media Type

Many teams use 400 for every validation failure, others use 422 for field-level errors. Either is fine; pick one and stay consistent. Never answer an error with status 200 and {"ok": false}: caches, monitors and client libraries all trust the status code.

One error format for the whole API

By default Flask renders errors such as 404 as HTML pages. That is useless to a program expecting JSON. Register a handler for HTTPException (the base class of every abort() error) so every error, including the automatic 404 and 405 ones, becomes JSON in the same shape. You learned the handler mechanics in Error Handling and Custom Error Pages.

A simple, useful error shape has a machine-readable code, a human message, and optional details:

JSON
{"error": {"code": "not_found", "message": "No note with id 99.", "details": {}}}
Python JSON errors for every failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same handler catches errors raised by your code (abort(404)), errors Flask raises itself (an unknown URL, a disallowed method) and errors you raise as your own ApiError. A client can now parse any failure with one piece of code.

Unhandled exceptions are a different case: they become 500 pages. In production you should also register @app.errorhandler(Exception) that logs the problem and returns a generic JSON 500 without leaking details. The debug-mode traceback must never reach API clients.

Content negotiation

Clients can say what they would like with the Accept header. A web page and an API sometimes share a URL, and one view answers in the format asked for. Werkzeug parses the header for you through request.accept_mimetypes:

  • request.accept_mimetypes.best_match([...]) picks the best offered type, or None if none fits.
  • request.accept_mimetypes.accept_json is a quick True / False check.

If nothing the client accepts is available, the correct answer is 406 Not Acceptable.

Python Answer in the format the client asks for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Do not over-engineer this. Most APIs simply always return JSON and ignore Accept; negotiation is worth it only when one URL truly serves several formats.

Useful habits

  • Prefix API routes with /api (or /api/v1) so they are easy to find, proxy and secure separately. Better still, put them in a Blueprint.
  • Keep JSON keys consistent: snake_case or camelCase, not both.
  • Return the created or updated object, so the client does not need a second request.
  • Do not return bare top-level lists if you may want to add pagination later; an object such as {"items": [...], "total": 40} can grow without breaking clients. Designing a REST API shows this in detail.
  • Never put secrets or password hashes in a response. Build the dict from an explicit list of fields instead of dumping a whole database row.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does request.get_json(silent=True) return when the body is not valid JSON?

    With silent=True, Flask suppresses the parsing error and returns None, so your own code can produce a JSON error response.
  2. 2. Which status code is the best answer for a successful POST that created a new resource?

    201 Created says a new resource exists now, and the Location header tells the client where to find it.
  3. 3. Why register an errorhandler for HTTPException in a JSON API?

    The default error responses are HTML. One HTTPException handler turns all of them, including automatic 404/405 errors, into your JSON error format.
  4. 4. A client sends Accept: image/png to a view that can produce only JSON, CSV and HTML. What is the correct response?

    406 Not Acceptable means the server cannot produce any representation the client said it accepts. Many APIs choose to ignore Accept and always send JSON, which is also acceptable if documented.

Summary

  • Return a dict, a list or jsonify(...) to send JSON; the content type is set for you.
  • request.get_json() reads the body: 415 for the wrong content type, 400 for broken JSON; silent=True returns None instead.
  • Use honest status codes: 201 for creation, 204 for empty success, 400/422 for bad input, 404, 405, 415, 406.
  • Register one handler for HTTPException plus your own exception class so every error has the same JSON shape.
  • request.accept_mimetypes.best_match(...) supports content negotiation; answer 406 when nothing fits.
  • Build responses from explicit fields; never leak secrets.

Next, step back from code and learn how resources, verbs and URLs fit together in Designing a REST API.