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')
]
Running and Testing the Django Application

To run the Django application, use the following command in your terminal:

python manage.py runserver 3000

This will start the Django development server in port 3000. You should see output indicating that the server is running.

To test the API endpoints, you can see the use tools like the preview window or curl. For example, to test the /api/generate_story/ endpoint using curl:

curl -X POST http://localhost:3000/api/generate_story/ -H "Content-Type: application/json" -d '{"prompt": "Once upon a time", "tone":"Epic"}'

This command sends a POST request with JSON data to the /api/generate_story/ endpoint. You should receive a response containing a generated story.

Summary and Next Steps

In this lesson, we built an API for our short story generation service using Django. We covered the creation of a basic Django application, implemented API endpoints for generating and retrieving stories, and integrated the StoryGeneratorController. You also learned how to run and test the application locally.

As you move on to the practice exercises, you'll have the opportunity to reinforce your understanding of building an API with Django. Feel free to experiment with modifying the API and adding new features. You've done an excellent job completing this course, and I encourage you to apply your knowledge to real-world projects. Well done!

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