Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Write a Python program to create a REST API using Django REST Framework.

  1. User

    Write a Python program to create a REST API using Django REST Framework.

  2. GLM Assistant

    The user wants a Python program to create a REST API using Django REST Framework (DRF).

    1. Understand the Goal: The goal is to provide a complete, working example of a simple REST API built with Django and DRF. This isn't just a snippet; it needs to be a guide or a set of code blocks that the user can actually run (assuming they have Python and Django installed).

    2. Determine the Scope:

    • Framework: Django + Django REST Framework.
    • Functionality: A basic CRUD (Create, Read, Update, Delete) API is the standard "Hello World" for REST.
    • Subject: A simple model like "Book" or "Task" is usually best for clarity. Let's go with "Book" (Title, Author, Publication Date).

    3. Structure of the Response: To make the program usable, I need to guide the user through the following steps:

    • Prerequisites (installation).
    • Project setup (creating project and app).
    • Model definition (models.py).
    • Serializer definition (serializers.py).
    • View definition (views.py).
    • URL configuration (urls.py - both app-level and project-level).
    • Settings configuration (settings.py).
    • Testing/Running instructions.

    4. Drafting the Code Steps:

    • Step 0: Installation pip install django djangorestframework

    • Step 1: Setup django-admin startproject myproject cd myproject python manage.py startapp books

    • Step 2: Settings (settings.py) Need to add 'rest_framework' and 'books' to INSTALLED_APPS.

    • Step 3: Model (books/models.py)

      from django.db import models
      
      class Book(models.Model):
          title = models.CharField(max_length=100)
          author = models.CharField(max_length=100)
          published_date = models.DateField()
      
          def __str__(self):
              return self.title
      
    • Step 4: Serializer (books/serializers.py) Need to create this file. It translates the Model to JSON.

      from rest_framework import serializers
      from .models import Book
      
      class BookSerializer(serializers.ModelSerializer):
          class Meta:
              model = Book
              fields = '__all__'
      
    • Step 5: View (books/views.py) I can use a generic class-based view or a ViewSet. For a beginner, ListCreateAPIView and RetrieveUpdateDestroyAPIView are explicit, but a ModelViewSet is more "DRF" style for quick setup because it handles routing automatically. Decision: Let's use ModelViewSet combined with a DefaultRouter. It demonstrates the power of DRF with less code.

      from rest_framework import viewsets
      from .models import Book
      from .serializers import BookSerializer
      
      class BookViewSet(viewsets.ModelViewSet):
          queryset = Book.objects.all()
          serializer_class = BookSerializer
      
    • Step 6: URLs

      • App level (books/urls.py): Setup the router.
        from django.urls import path, include
        from rest_framework.routers import DefaultRouter
        from .views import BookViewSet
        
        router = DefaultRouter()
        router.register(r'books', BookViewSet)
        
        urlpatterns = [
            path('', include(router.urls)),
        ]
        
      • Project level (myproject/urls.py): Include the app urls.
        from django.contrib import admin
        from django.urls import path, include
        
        urlpatterns = [
            path('admin/', admin.site.urls),
            path('api/', include('books.urls')), # Prefix with api/
        ]
        
    • Step 7: Execution python manage.py makemigrations python manage.py migrate python manage.py runserver

    5. Refinement and Verification:

    • Is the code syntactically correct? Yes.
    • Is the folder structure clear? I should explicitly state where files go.
    • How does the user test it? Mention the browsable API (a key DRF feature) and curl/Postman.

    6. Final Polish:

    • Add comments explaining why we are doing each step.
    • Keep it concise.

    (Self-Correction during drafting): Initially, I thought about using function-based views (@api_view). However, Class-Based Views (CBVs) or ViewSets are more standard for DRF. ViewSets are the most efficient for a "write a program" request because they generate the whole CRUD structure automatically. I will stick with ModelViewSet.

    7. Constructing the Final Output: (This aligns with the provided good response, organizing by file name and providing the terminal commands). Here is a complete, step-by-step guide to creating a simple REST API using Django and Django REST Framework (DRF).

    We will build a simple API to manage Books (CRUD: Create, Read, Update, Delete).

    Prerequisites

    First, install Django and Django REST Framework via your terminal:

    pip install django djangorestframework
    

    Step 1: Set up the Project and App

    Run the following commands in your terminal to create the project structure:

    # 1. Create the Django project
    django-admin startproject bookstore
    
    # 2. Navigate into the folder
    cd bookstore
    
    # 3. Create an app to handle the API
    python manage.py startapp books
    

    Step 2: Configure Settings

    Open bookstore/settings.py. You need to add 'rest_framework' and your new app 'books' to the INSTALLED_APPS list.

    # bookstore/settings.py
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        
        # Add these two lines:
        'rest_framework', 
        'books',
    ]
    

    Step 3: Create the Model

    Define the database structure in books/models.py.

    # books/models.py
    from django.db import models
    
    class Book(models.Model):
        title = models.CharField(max_length=100)
        author = models.CharField(max_length=100)
        published_date = models.DateField()
    
        def __str__(self):
            return self.title
    

    Step 4: Create the Serializer

    Serializers convert complex data (like model instances) into JSON format. Create a new file named books/serializers.py.

    # books/serializers.py
    from rest_framework import serializers
    from .models import Book
    
    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
            fields = ['id', 'title', 'author', 'published_date']
    

    Step 5: Create the View

    We will use a ModelViewSet. This is a special shortcut in DRF that automatically provides the logic for listing, creating, retrieving, updating, and deleting.

    Edit books/views.py:

    # books/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
    

    Step 6: Configure URLs

    We need to wire up the URLs so the browser can access the view.

    1. Create books/urls.py: Create this file inside your books app folder.

    # books/urls.py
    from django.urls import path, include
    from rest_framework.routers import DefaultRouter
    from .views import BookViewSet
    
    # Create a router and register our ViewSet with it.
    router = DefaultRouter()
    router.register(r'books', BookViewSet)
    
    # The API URLs are now determined automatically by the router.
    urlpatterns = [
        path('', include(router.urls)),
    ]
    

    2. Update the project urls.py: Open bookstore/urls.py (note the slight name difference from the app folder) and include the app URLs.

    # bookstore/urls.py
    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/', include('books.urls')), # Forward API requests to the books app
    ]
    

    Step 7: Run Database Migrations

    Since we created a model, we need to create the table in the database. Run these commands in your terminal:

    python manage.py makemigrations
    python manage.py migrate
    

    Step 8: Run the Server

    Start the development server:

    python manage.py runserver
    

    How to Test the API

    Open your web browser and go to: http://127.0.0.1:8000/api/books/

    You will see the Django REST Framework Browsable API. This is a visual interface provided by DRF.

    1. Read (GET): You will see an empty list [] initially.
    2. Create (POST): Fill out the form at the bottom of the page (in the "HTML form" section) with a Title, Author, and Date (e.g., 2023-01-01) and click POST.
    3. Detail (GET/PUT/DELETE): After creating a book, the list will show it. You can click on the specific book URL (e.g., /api/books/1/) to view its details, update them (PUT), or delete the record (DELETE).

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.