Creating a Django REST API
The user wants a Python program to create a REST API with Django REST Framework. It looks like they’re looking for sample code, including project setup, app, serializers, views, and URLs. They didn't specify a model, so I should consider a simple example like a "Book" model with basic GET/POST/PUT/DELETE operations. I’ll provide step-by-step instructions on installation, project creation, and how to run tests with concise code blocks. I want to keep it beginner-friendly!Structuring the Django REST API
To create the Django REST API, I need to outline clear steps and provide the necessary commands and file structures. I think starting with function-based APIView or class-based generics makes sense; generics are easier for beginners. A "Book" model with fields like id, title, author, and published_date could work well for this example.
I’ll include installation steps, project and app creation commands, and necessary settings modifications within the project structure. It’s crucial to format my response concisely and step by step, incorporating code blocks!Clarifying the Python Program Request
I need to determine what the user means by "Python program"; they might prefer code in a .py file rather than shell commands, although including both could make sense. I'll structure my response with clear steps:
- Setup and installation commands
- Create the project and app commands
- Code snippets for key files like settings.py, models.py, serializers.py, views.py, and urls.py; I’ll keep it brief with only the necessary code.
I’ll use SQLite by default and illustrate with a "Book" model example, ensuring I show the correct import paths!Creating Serializers and ViewSets
For the Django REST API, I’ll start by defining a serializer for the "Book" model. The BookSerializer will use Django REST Framework's ModelSerializer to handle all fields.
Next, the BookViewSet will be created using the ModelViewSet, which simplifies CRUD operations for the Book model.
In api/urls.py, I’ll set up a router that connects the viewset to the API endpoints, allowing users to perform actions like GET /api/books/ and POST /api/books/. I might also mention the browsable UI and REST_FRAMEWORK settings!Structuring the Django Setup
I’m considering what the user might want. They might expect everything in a single main script, but that’s a bit advanced for normal Django setups. It’s better to follow the standard project and app structure.
So, I’ll create a structured, clear recipe for setting up the Django REST API. I need to keep the explanations minimal but also ensure they’re clear. I’ll focus on providing concise instructions that make it easy for the user to follow along! Below is a minimal, full example of creating a CRUD REST API with Django REST Framework.
It will expose /api/books/ where you can GET, POST, PUT, PATCH, and DELETE books.
1. Install dependencies
pip install django djangorestframework
2. Create Django project and app
django-admin startproject myproject
cd myproject
python manage.py startapp api
Project structure will look like:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
...
api/
__init__.py
admin.py
apps.py
models.py
views.py
...
3. Configure settings.py
Edit myproject/settings.py and add the new apps:
INSTALLED_APPS = [
# Django apps...
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party
'rest_framework',
# Your app
'api',
]
(You can skip REST_FRAMEWORK config for a basic setup.)
4. Create a model
Edit api/models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_date = models.DateField(null=True, blank=True)
def __str__(self):
return self.title
Apply migrations:
python manage.py makemigrations
python manage.py migrate
(Optional) Register in admin so you can see data in the admin site:
# api/admin.py
from django.contrib import admin
from .models import Book
admin.site.register(Book)
5. Create a serializer
Create api/serializers.py:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__' # or list specific fields: ['id', 'title', 'author', 'published_date']
6. Create API views
Use a ModelViewSet to get full CRUD automatically.
Edit api/views.py:
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
7. Wire up URLs
Create api/urls.py:
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet, basename='book')
urlpatterns = router.urls
Then include these URLs from the main project URLs.
Edit myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')), # /api/books/
]
8. Run the development server
python manage.py runserver
Now you can use:
- Browser:
http://127.0.0.1:8000/api/books/ – list & create books
http://127.0.0.1:8000/api/books/1/ – retrieve, update, delete book with ID 1
- Example
curl commands:
# Create
curl -X POST http://127.0.0.1:8000/api/books/ \
-H "Content-Type: application/json" \
-d '{"title": "My Book", "author": "Alice", "published_date": "2025-01-01"}'
# List
curl http://127.0.0.1:8000/api/books/
# Update
curl -X PUT http://127.0.0.1:8000/api/books/1/ \
-H "Content-Type: application/json" \
-d '{"title": "Updated", "author": "Alice", "published_date": "2025-01-02"}'
# Delete
curl -X DELETE http://127.0.0.1:8000/api/books/1/
If you’d like, I can collapse this into a checklist or add authentication/pagination examples.