Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 77 ยท REST APIs

Building JSON APIs with Plain Django

Build a JSON API with plain Django: JsonResponse, serializing models, parsing request bodies, status codes, validation, pagination and consistent error responses.

A JSON API lets programs talk to your Django site: a mobile app, a JavaScript front end, another server. Instead of HTML pages, your views accept and return JSON. You do not need a special library to do this. Django already has everything required: JsonResponse to send JSON, json.loads(request.body) to read it, and the URL and view machinery you know.

In this lesson you will build a small but complete CRUD API (create, read, update, delete) with plain Django. Writing it by hand once is the best way to understand what a framework like Django REST Framework (covered later) automates for you. You should be comfortable with function-based views and request data first.

What an API view does differently

An HTML view renders a template. An API view does four other jobs, and a clean API handles each of them in a predictable way:

flowchart LR
    C["Client<br/>(JSON request)"] --> P["Parse body<br/>(400 if invalid)"]
    P --> V["Validate data<br/>(422 with field errors)"]
    V --> D["ORM: create, read,<br/>update, delete"]
    D --> S["Serialize to dict"]
    S --> R["JsonResponse<br/>+ status code"]

Every request is parsed, validated, handled by the ORM, serialized and returned with the right status code.

Sending JSON

JsonResponse takes a dictionary, converts it with json.dumps and sets the Content-Type: application/json header. It uses Django's JSON encoder, which also knows how to write dates, times, Decimal values and UUIDs, so you do not have to convert those yourself.

By default JsonResponse refuses anything except a dictionary (a historical security precaution about top-level arrays). To return a list, pass safe=False. Many API designers avoid the issue by always returning an object like {"results": [...]}, which also leaves room for extra fields such as counts.

Serializing a model means turning an instance into a plain dictionary. Writing a small function for this keeps you in control of exactly which fields are public. Do not expose everything blindly: a User row contains a password hash.

Reading JSON

Django parses request.POST only for form submissions. A JSON body arrives raw in request.body (bytes), and you parse it yourself with json.loads. Two things can go wrong, and both are the client's fault, so both deserve a 400 Bad Request:

  1. The text is not valid JSON, so json.loads raises json.JSONDecodeError.
  2. The JSON is valid but not an object (for example a bare number or a list) when you expect one.

The first example covers serialization and parsing with a Book model.

Python JsonResponse, serializing and parsing

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 book JSON: the Decimal price became the string "9.99" and the date became "1965-08-01". That is deliberate. JSON has no decimal or date type, and strings are the safe choice for money, because a floating-point number could introduce rounding errors. The secret_note field never appears because book_to_dict does not mention it. The last loop shows three bodies: only the first is accepted.

Status codes that mean something

Clients rely on the status code to decide what to do next, so choose it carefully:

Situation Status
Successful read or update 200 OK
Resource created 201 Created (with a Location header)
Successful delete with nothing to return 204 No Content
Malformed JSON or bad query parameter 400 Bad Request
Valid JSON, but data fails validation 422 Unprocessable Content (some APIs use 400)
Not logged in 401 Unauthorized
Logged in but not allowed 403 Forbidden
No such resource 404 Not Found
Method not supported on this URL 405 Method Not Allowed

Never return 200 OK with {"error": ...} in the body. Generic tools, caches and monitoring all look at the status.

A complete CRUD API

Now put it all together for a Task resource. The design is the usual REST layout with two URLs:

  • /tasks/ supports GET (list, with filtering and pagination) and POST (create).
  • /tasks/<id>/ supports GET (read), PUT (replace), PATCH (partial update) and DELETE.

Notice how the code is organized. A custom ApiError exception carries a status and a message, a small decorator turns it into a consistent JSON error body, and all views raise instead of building error responses by hand. That keeps each view short.

Browsers protect cookie-based sessions with CSRF tokens, and Django enforces this on POST, PUT, PATCH and DELETE. APIs that authenticate with a token in the Authorization header are not vulnerable to CSRF, so they mark views with @csrf_exempt. Never exempt views that rely on session cookies for login. The test client skips CSRF checks by default, which is why the demo works without tokens.

Python A CRUD API for tasks

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.

Read the output from top to bottom and match each line with the code. Creating returns 201 plus a Location header pointing at the new task; reading a missing task returns 404 with the same error shape as every other failure; PATCH changes only the fields you send, while PUT requires a complete representation (here, a title); DELETE returns 204 with an empty body. The list endpoint returns count, pages and the current page of results, and filters with ?done=true.

Because every failure goes through ApiError, a client only needs to handle one error shape: {"error": {"code": ..., "message": ..., "fields": {...}}}. A stable machine-readable code is worth adding, because messages are for humans and may change.

Things a real API still needs

The code above is a solid base, but a production API adds more:

  • Authentication and permissions. Decide who may read or change each resource. See Users and Authentication and the token patterns in the next lesson, API Design, Versioning and CORS.
  • Rate limiting to protect against abuse, usually in a reverse proxy or a cache-backed counter.
  • Query efficiency. Serializing related objects in a loop causes N+1 queries; use select_related as shown in ORM Performance.
  • Documentation and tests. Test every endpoint with the test client, as described in Testing Django Apps.

When the number of endpoints grows, hand-written parsing and validation get repetitive. That is the moment to adopt a library such as Django REST Framework.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you return a top-level JSON list from JsonResponse?

    By default JsonResponse accepts only a dict. Passing safe=False allows other JSON types such as lists.
  2. 2. A client sends the body 'not json'. Which status code is the most appropriate response?

    The request itself is malformed, which is the client's mistake: 400 Bad Request. Do not return 200 with an error message in the body.
  3. 3. Where does a JSON request body arrive in a Django view?

    request.POST is only filled for form-encoded data. JSON arrives raw in request.body.
  4. 4. What is the main difference between PUT and PATCH in this lesson's API?

    PUT sends a complete representation. PATCH is a partial update, so the validation treats missing fields as unchanged.
  5. 5. Why might a money field be serialized as a string such as '9.99'?

    Many JSON parsers read numbers as floating point. A string keeps the exact decimal value and lets the client decide how to parse it.

Summary

  • JsonResponse sends JSON; use safe=False for lists, or wrap results in an object.
  • Parse request bodies with json.loads(request.body) and answer bad input with 400.
  • Serialize models with an explicit function so only intended fields are exposed.
  • Choose meaningful status codes: 200, 201 with Location, 204, 400, 404, 405 and 422 for validation errors.
  • Centralize errors with an exception and a decorator so every failure has the same JSON shape.
  • Paginate and filter list endpoints, validate every input, and add authentication before going public.

Next lesson: API Design, Versioning and CORS.