Building a Django API

Introduction: What You’ll Build and Why

Welcome! In this lesson, you’ll build a simple Django app from scratch using Codex, focusing on creating a Dice Roller API. This API will let you roll any number of dice with any number of sides and return the results as JSON, making it a practical way to get hands-on with Django and Codex. You’ll start by setting up a new Django project and app, then add the core logic for rolling dice, and finally expose this functionality through a web API endpoint. By the end of the lesson, you’ll have a working endpoint that you can test using the platform’s Preview feature, giving you a solid foundation in Django API development before moving on to more advanced features like dice notation and roll history.

Project Setup: Starting From Scratch

Let’s begin by creating a new Django project and app. If you’re new to Django, a “project” is the overall web application, and an “app” is a component inside it (like a module).

To get started, you’ll need Python 3.10+ and Django 4.2+ installed. It’s best to use a virtual environment.

Here’s how you can ask Codex to help you set up the project:

Create a Django project called diceroller and inside it a Django app called dice. Add 'dice' to INSTALLED_APPS in settings.py and set ALLOWED_HOSTS = ["*"] so it works on the platform.

What happens here?

  • Codex will generate the commands to create a new Django project named diceroller.
  • It will also create an app called dice, register it in INSTALLED_APPS, and configure ALLOWED_HOSTS so the platform accepts incoming requests.

This sets up the basic structure you need to start building your app.

Adding Core Logic: The Dice Rolling Function

Next, let’s add the core logic: a function that rolls dice. We want a function that takes two numbers — how many dice to roll (count) and how many sides each die has (sides) — and returns a list of random results.

You can ask Codex to help you with this:

In dice/utils.py, add a function roll_dice(count, sides) that returns random rolls.

Codex will create utils.py inside your dice app with something like:

import random

def roll_dice(count, sides):
    return [random.randint(1, sides) for _ in range(count)]

Explanation:

  • random.randint(1, sides) generates a number between 1 and the number of sides (inclusive).
  • The list comprehension repeats this for however many dice you roll.

This function is the heart of your Dice Roller.

Building The API Endpoint

While Django REST Framework (DRF) is commonly used for building APIs in Django, we're using plain Django views with JsonResponse here. This approach is simpler and sufficient for our needs, especially since we'll be building a user interface later in this course. If you were building a production API that only serves JSON, DRF would be the better choice.

Now, let's make this functionality available through a web API. We'll create a view that reads the count and sides from the URL's query parameters, uses your roll_dice function, and returns the results as JSON.

Prompt Codex like this:

In dice/views.py, add a view roll that reads count and sides from query params, calls roll_dice, and returns a JsonResponse with rolls and total.

Example Codex output:

from django.http import JsonResponse
from .utils import roll_dice

def roll(request):
    count = int(request.GET.get('count', 1))
    sides = int(request.GET.get('sides', 6))
    rolls = roll_dice(count, sides)
    return JsonResponse({'rolls': rolls, 'total': sum(rolls)})

To make this view accessible, ask Codex:

Add dice/urls.py with a route /roll/ to the roll view. Include this in the main urls.py.

This will:

  • Create a urls.py in your dice app with a route for /roll/.
  • Update your main diceroller/urls.py to include the dice app’s URLs.

Running and Testing

Now it’s time to see your work in action. First, make sure your database is set up:

python3 manage.py migrate

Then start the server with this command (important for the platform):

python3 manage.py runserver 0.0.0.0:3000

Explanation:

  • 0.0.0.0 makes Django listen on all interfaces (not just localhost).
  • :3000 ensures the app runs on port 3000, which the platform exposes.

Once the server is running, open the platform’s Preview for port 3000 and test:

<your-preview-url>/roll/?count=3&sides=6

You should see a JSON response like:

{"rolls":[2,5,4],"total":11}

This means you rolled three six-sided dice and got results 2, 5, and 4. The total is 11.

Summary And What’s Next

In this lesson, you set up a new Django project and app with Codex's help, wrote a utility function to roll dice, and built an API endpoint that returns dice rolls as JSON. You also learned how to run your Django server on the platform using the correct command so it's accessible for testing. With these steps, you now have a working Dice Roller API that you can interact with through your browser or API tools. In the next lesson, you'll build a user-friendly landing page with an interactive interface for your dice roller.

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