Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 39 ยท Getting Started

Your First API View

Build list, create, detail, update and delete endpoints with DRF's @api_view decorator, a model and a serializer, and test each one with APIClient.

The quickest way to write a DRF endpoint is a function-based view wrapped in the @api_view decorator. It looks like an ordinary Django view, but the decorator swaps Django's request for a richer DRF Request, makes your return value a DRF Response, rejects methods you did not list and turns exceptions into proper JSON errors.

In this lesson you will build the classic five operations for a Book resource: list, create, retrieve, update and delete. You already know the shape of a Django model and URL; the new parts are the decorator, Response and the serializer that connects the two.

The decorator and the rules it enforces

Python
from rest_framework.decorators import api_view
from rest_framework.response import Response


@api_view(["GET", "POST"])
def book_list(request):
    ...

@api_view(["GET", "POST"]) does four things:

  1. It wraps your function so it receives a DRF Request (with request.data and request.query_params).
  2. It returns 405 Method Not Allowed for every method that is not in the list (OPTIONS is answered automatically).
  3. It runs authentication, permission and throttle checks (configured globally or per view, covered in the Authentication and Permissions chapter).
  4. It catches exceptions such as Http404 and PermissionDenied and renders them as JSON error responses.

If you forget the decorator, a plain function returning Response fails, because Response needs the DRF machinery to be rendered.

A list and create endpoint

The model and serializer below are the ones used throughout this lesson. Notice class Meta: app_label = "library": a normal project creates models inside an app package; here the tab has no package, so the label is stated explicitly, and create_model builds the table the way a migration would.

Python List and create books

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 GET branch builds a serializer from a queryset with many=True, which produces a list. The POST branch passes request.data to the serializer, validates, saves and returns the saved representation with status 201 Created. When validation fails, serializer.errors becomes the body of a 400 Bad Request. The final DELETE shows the decorator at work: the list view never mentions DELETE, so the answer is 405.

Use the named constants from rest_framework.status (HTTP_201_CREATED, HTTP_404_NOT_FOUND) rather than bare numbers. They read like words, and a typo becomes an error instead of a wrong status.

A detail endpoint: retrieve, update, delete

A URL with an identifier addresses one resource: /books/3/. The usual mapping is GET to read, PUT to replace, PATCH to change some fields and DELETE to remove it.

Python Retrieve, update and delete one book

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.

Three details matter here.

  • get_object_or_404 raises Http404, which DRF turns into a JSON 404 with {"detail": "No Book matches the given query."} (the wording comes from Django). You never write the error response yourself.
  • partial=True tells the serializer that missing fields are allowed. That is the only difference between PUT (full replacement) and PATCH (partial update). The failing PUT shows a field-level error for the missing title.
  • raise_exception=True replaces the if is_valid(): ... else: return Response(errors, 400) pattern. If validation fails, DRF raises a ValidationError that is rendered as a 400 automatically. This keeps handlers short.

Writing reusable handlers

Notice how similar the two views are to every other resource you will write: fetch, serialize, validate, save, respond. That repetition is exactly why DRF also provides class-based views, generic views and ViewSets, which you will meet in Views and ViewSets. Function-based views remain a good choice for one-off endpoints that do not map to a model, such as /health/, /login/ or a report.

flowchart TD
    A["@api_view(['GET', 'PUT', 'DELETE'])"] --> B{"request.method"}
    B -->|GET| C["serialize and return"]
    B -->|PUT / PATCH| D["validate, save, return"]
    B -->|DELETE| E["delete, return 204"]
    B -->|anything else| F["405 Method Not Allowed"]

The decorator filters methods first; your code then branches on request.method.

Common mistakes

  • Returning a Django JsonResponse. It works, but you lose content negotiation and the browsable API. Return Response.
  • Forgetting many=True when serializing a queryset. Without it the serializer expects a single object and the output is wrong.
  • Calling serializer.data before is_valid() when you passed data=. DRF raises an assertion error, because there is nothing validated yet.
  • Using 200 for creation. Use 201 for a newly created resource and 204 for a successful response without a body.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @api_view(["GET"]) do when a client sends POST?

    Methods not listed in the decorator are rejected with 405 before your function runs.
  2. 2. Which status code should a successful create return?

    201 Created tells the client a new resource now exists. The body usually contains it.
  3. 3. What is the difference between PUT and PATCH handling with a serializer?

    partial=True relaxes the 'required' rule, so a PATCH body may contain only the fields to change.
  4. 4. What does serializer.is_valid(raise_exception=True) do on invalid input?

    The exception is handled by DRF's exception handler and turned into a JSON 400 with the errors.

Summary

  • @api_view([...]) turns a function into a DRF view with a DRF Request, Response and automatic error handling.
  • Lists use many=True; creation returns 201; deletion returns 204 with no body.
  • Detail views fetch with get_object_or_404 and use partial=True for PATCH.
  • is_valid(raise_exception=True) keeps handlers short by letting DRF render validation errors.
  • Prefer rest_framework.status constants over bare numbers.

Next: Request, Response and Status Codes