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.
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:
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_exemptis used to allow POST requests without CSRF tokens for simplicity.generate_storyhandles POST requests, extractspromptfrom the JSON payload, and calls the controller to generate a story.get_storieshandles GET requests and retrieves all generated stories.
Next, update your generator/urls.py to include these endpoints:
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.
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!
