Last modified: Mar 10, 2025 By Alexander Williams
Setting Up Your First API with Django Rest Framework
Django Rest Framework (DRF) is a powerful tool for building APIs in Django. It simplifies the process of creating RESTful APIs. This guide will walk you through setting up your first API.
Table Of Contents
Prerequisites
Before starting, ensure you have Django installed. If not, follow our guide on How to Install Django Rest Framework Step by Step.
Creating a Django Project
First, create a new Django project. Use the django-admin
command to set up your project.
django-admin startproject myproject
Navigate into your project directory.
cd myproject
Installing Django Rest Framework
Install DRF using pip. This will add the necessary packages to your Django project.
pip install djangorestframework
Add 'rest_framework' to your INSTALLED_APPS
in settings.py
.
INSTALLED_APPS = [
...
'rest_framework',
]
Creating a Simple API
Let's create a simple API. Start by creating a new app within your Django project.
python manage.py startapp myapi
Add 'myapi' to INSTALLED_APPS
in settings.py
.
INSTALLED_APPS = [
...
'myapi',
]
Defining a Model
Define a simple model in models.py
of your new app.
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
Run migrations to apply the model to your database.
python manage.py makemigrations
python manage.py migrate
Creating a Serializer
Serializers allow complex data types to be converted to Python datatypes. Create a serializer for the Item model.
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ['id', 'name', 'description']
Setting Up Views
Use ListCreateAPIView
to handle GET and POST requests. Learn more about it in our Django Rest Framework ListCreateAPIView Example.
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer
class ItemList(generics.ListCreateAPIView):
queryset = Item.objects.all()
serializer_class = ItemSerializer
Configuring URLs
Finally, configure URLs to access your API. Add the following to your urls.py
.
from django.urls import path
from .views import ItemList
urlpatterns = [
path('items/', ItemList.as_view()),
]
Testing Your API
Run your server and test the API using a tool like Postman or curl.
python manage.py runserver
Visit http://127.0.0.1:8000/items/
to see your API in action.
Conclusion
You've successfully set up your first API with Django Rest Framework. This is just the beginning. Explore more advanced features like permissions and custom views in our Django Rest Framework IsAdminUser Permission Examples.