Skip to main content

Command Palette

Search for a command to run...

Building your first API with Django Rest Framework(DRF) - A beginner's guide

Updated
8 min read
Building your first API with Django Rest Framework(DRF) - A beginner's guide

Hello! 👋 Welcome to Building Your First API with DRF — A Beginner’s Guide! 🚀

Building on my previous article on setting up a Django REST Framework (DRF) project — which serves as a prerequisite for this one — we’ll be taking things a step further by actually creating a functional API using Django REST Framework.

We’ll be building a simple Todo List API in this article. You’ll learn how to perform basic CRUD operations — POST, GET, DELETE, and UPDATE — using Django Rest Framework (DRF).

Let’s get started! 🚀

The first thing we’ll do is create a new app inside the myproject folder we used in the previous tutorial.

Step 1: Open the project in VS Code.

You should see your project structure in the sidebar, with your virtual environment already activated:

Next, we need to register this new app in our Django environment.
Open the settings.py file inside your main project folder (which should be myproject, or whatever name you used).
Scroll down to the INSTALLED_APPS section in your settings.py file, and add both 'todolist' and 'rest_framework' to the list. This step lets Django know that the new app we just created and the Django Rest Framework are part of the project.

Step 2: In your terminal, run the command python -m django startapp todolist.

Once you do that, a new directory named todolist will appear in your project folder, that’s where all the files related to this app will live.

Now, let’s kickstart our development server by running python manage.py runserver in your terminal.
If everything is set up correctly, you shouldz see a local server URL (something like http://127.0.0.1:8000/) displayed in your terminal.

Step 3: Write your API model

Models in Django represent the structure of your database tables and define the data your API will work with. For our simple Todo List API, we'll create a Todo model in the tutorial app. This model will include fields that capture essential fields of a todolist app.

A typical todolist app would have fields such as, title, content, completed (a boolean to mark if the task is done), and created_at (a timestamp for when the task was added).

To implement this in your Django app, open the todolist/models.py file (create it if it doesn't exist) and define a simple Todo model like this:

A quick breakdown of what each of the field does to help you understand the model:

  • The title field is a short string for the task's name. It uses Django's CharField, which is designed for fixed-length strings and requires a max_length parameter (set to 200 here) to limit input size for efficient database storage.

  • The content field holds longer, multi-line text for task details or descriptions. It uses TextField, which is suitable for unlimited or variable-length text without a strict character limit, making it ideal for more descriptive content.

  • The completed field is a boolean value (True or False) to indicate if the task is done. It uses BooleanField with a default=False, so new tasks start as incomplete unless you specify otherwise.

  • The created_at field automatically records the date and time when the task is created. It uses DateTimeField, which stores datetime values, and the auto_now_add=True option sets it once on creation without needing manual input.

  • Finally, the str method isn't a field but a special method that provides a human-readable string representation of the model instance (e.g., for the Django admin panel or debugging). In this case, it simply returns the task's title for easy identification.

    Now that we’ve defined the model, we need to update the database schema. Run these commands in your terminal:

    1. python manage.py makemigrations – This generates migration files based on your model changes.

    2. python manage.py migrate – This applies those migrations to create the actual table in your database.

If you encounter any errors, double-check your code structure and ensure your virtual environment is active. Once that's done, your data structure is ready, and we can move on to serializing this model for API use in the next step.

Step 4: Create a Serializer for Your Model

Serializer in Django Rest Framework is like a middleman between the models and views (which we’ll get to shortly). Its job is to take complex data like your Django model objects and turn them into simple formats such as JSON or XML. It also does the reverse by taking incoming data (like from an API request) and converting it back into Django objects your app can work with.

For our todo list app, we’ll create a simple serializer to process the incoming and outgoing data between our Todo model and the API endpoints.

To do this, you’ll to create a new file named serializers.py. it should be in todolist folder. type in the code in the image below:

A quick breakdown to help you understand the serializer:

  • We import serializers from DRF and our Todo model.

  • TodoSerializer inherits from ModelSerializer, which automatically generates fields based on the model,saving you from manually defining each one.

  • In the Meta class:

    • model = Todo specifies which model this serializer is for, which is our Todo model.

    • fields lists the model fields to include in the serialized output. We've added 'id' (automatically created by Django for each model instance) along with the fields we defined earlier. You could use fields = '__all__' to include everything, but explicitly listing them is better for control and security.

Step 5: Creating API Views

Views in DRF handle the logic for processing incoming requests (GET, POST, PUT, DELETE) and returning responses. It leverages on the serializer to convert data to and from JSON. For a simple CRUD API like our Todo list, DRF provides powerful tools like ViewSets to minimize boilerplate code.

We'll use a ModelViewSet, which automatically provides standard actions for listing, retrieving, creating, updating, and deleting model instances.

Note: A model instance is a single, concrete piece of data, like a filled-out form that follows the blueprint of your model's defined fields, representing one row in your database that you can create, read, update, or delete.

Navigate to your views.py file in the todolist folder, if you don’t already have one you can create one called views.py in the todolist app directory.

A quick breakdown to help you understand the view:

  • We import viewsets from DRF, along with our Todo model and TodoSerializer.

  • TodoViewSet inherits from ModelViewSet, which gives us out-of-the-box support for CRUD operations without writing separate methods for each.

  • queryset defines the base set of objects(data) the view will work with, in this case, all Todo items(objects, data), ordered by created_at in descending order (newest first).

  • serializer_class points to our TodoSerializer, which handles data serialization/deserialization for requests and responses.

Step 6: Define the URLs for your API endpoints

Now that we’ve set up our view, serializer, and model, we need to define URLs for each of our endpoints so the client side (like a web app or mobile app) can interact with our database—like fetching a list of todos or adding a new one.

First, we need to create a new file called urls.py in our todolist app folder, then we'll use a router to automatically generate these URL patterns for our TodoViewSet. The router will create endpoints like /todos/ for listing/creating and /todos/{id}/ for details.

Next, navigate to the main urls.py file inside your myproject folder. This is where you’ll connect your app’s URL routes to the main project, so Django knows how to direct incoming requests to your API endpoints.

A quick breakdown of what's happening:

  • In todolist/urls.py:

    • DefaultRouter is a DRF's class that automatically handles URL routing for your viewset, it goes through the TodoViewSet and builds URLs for all CRUD actions automatically.

    • router.register(r'todos', TodoViewSet) sets 'todos' as the base path (e.g., /api/todos/). The r prefix treats the string literally so it doesn’t interprete the backslash as an escape character (like \n for a new line).

    • path('', include(router.urls)) bundles everything from the router into one clean list.

  • In the main urls.py:

Your API is now live! Restart your development server using python manage.py runserver. Then open your browser and navigate to http://127.0.0.1:8000/api/todos/ — you should see an empty JSON array [] since no data has been added yet.

You’ll notice a form with the field names we defined in our model. We can use this interface to send a POST request through our API. Simply fill in the input fields as shown below:

After filling in the fields, click “POST”. If the request is successful, you’ll see a response similar to the one shown below, along with a 201 HTTP status code.

Conclusion:
And that’s it! 🎉 You’ve just built a simple yet functional Todo List API using Django REST Framework. Along the way, you learned how to create a new Django app, define models, serializers, and views, and set up URL routes to connect everything together.

In my next article, I’ll be walking you through how to add a custom user model and implement user authentication in Django Rest Framework. Stay tuned! Keep coding and keep exploring! 🚀