Building an API for the Short Story Generator with Django

Introduction to Django and API Development

In this lesson, we will build an API for our short story generation service using the Django framework. In previous lessons, we created components such as the PromptManager, StoryManager, and StoryGeneratorService. Now, we will connect these components by building a Django API that will serve as the backbone of our application. An API (Application Programming Interface) allows different software components to communicate with each other. In our case, it will enable users to interact with our story generation service through HTTP requests.

Creating a Basic Django Application

Let's start by defining a simple view that will render the homepage. In your generator/views.py file, add the following code:

from django.http import HttpResponse

def index(request):
    return HttpResponse("Welcome to the Short Story Generator!")

This function returns a simple welcome message when the root URL is accessed.

Now, set up the URL configuration for your app. In generator/urls.py, add:

from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='index'),
]

Finally, include your app's URLs in the project's main URL configuration. In project/urls.py, add:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('generator.urls')),
]

Implementing API Endpoints

Now, let's implement the API endpoints that will handle story generation and retrieval.

First, define the view functions for generating and retrieving stories in generator/views.py:

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt
def generate_story(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        prompt = data.get('prompt')
        return story_generator_controller.generate_story(prompt)
    return JsonResponse({'error': 'Invalid request method'}, status=405)

def get_stories(request):
    if request.method == 'GET':
        return story_generator_controller.get_stories()
    return JsonResponse({'error': 'Invalid request method'}, status=405)
  • @csrf_exempt is used to allow POST requests without CSRF tokens for simplicity.
  • generate_story handles POST requests, extracts prompt from the JSON payload, and calls the controller to generate a story.
  • get_stories handles GET requests and retrieves all generated stories.

Next, update your generator/urls.py to include these endpoints:

from django.urls import path
from .views import index, generate_story, get_stories

urlpatterns = [
    path('', index, name='index'),
    path('api/generate_story/', generate_story, name='generate_story'),
    path('api/get_stories/', get_stories, name='get_stories')
]
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal