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:

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:

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

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:

  • @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:

Running and Testing the Django Application

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

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:

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