Building Dice Roller API

Introduction: What You'll Build and Why

Welcome! In this lesson, you'll build a simple Express application 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 Express, TypeScript, and Codex. You'll start by setting up a new Express project with TypeScript, 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 express 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 Express application with TypeScript. If you're new to Express, it's a minimal web framework that makes building APIs straightforward.

To get started, you'll need Node.js 18+ installed. You'll use npm (Node Package Manager) to manage dependencies.

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

plaintext
Create a new Express TypeScript project called diceroller. Initialize with npm, add TypeScript, Express, and @types/express. Create a tsconfig.json for TypeScript compilation and a basic server structure in src/index.ts that listens on port 3000.

What happens here?

  • Codex will generate commands to initialize a new Node.js project with npm init.
  • It will install Express, TypeScript, and necessary type definitions.
  • It will create a tsconfig.json file to configure TypeScript compilation.
  • It will set up a basic Express server in src/index.ts that listens on the correct port.

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:

plaintext
Create src/utils.ts with a function rollDice that takes count and sides as parameters and returns an array of random rolls. Use TypeScript type annotations.

Codex will create utils.ts inside your src folder with something like:

TypeScript
export const rollDice = (count: number, sides: number): number[] => {
    const rolls: number[] = [];
    for (let i = 0; i < count; i++) {
        rolls.push(Math.floor(Math.random() * sides) + 1);
    }
    return rolls;
};

Explanation:

  • Math.random() generates a number between 0 and 1.
  • Math.random() * sides scales it to the number of sides.
  • Math.floor() rounds down, and adding 1 gives us a range from 1 to sides (inclusive).
  • The function uses type annotations (: number, : number[]) to ensure type safety.
  • export const makes this function available to other files.

This function is the heart of your Dice Roller.

Building The API Endpoint

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

Prompt Codex like this:

plaintext
In src/index.ts, add a GET route /roll that reads count and sides from query parameters, calls rollDice, and returns JSON with rolls and total. Import rollDice from utils.ts.

Example Codex output:

TypeScript
import express, { Request, Response } from 'express';
import { rollDice } from './utils';

const app = express();
const PORT = 3000;

app.get('/roll', (req: Request, res: Response) => {
    const count = parseInt(req.query.count as string) || 1;
    const sides = parseInt(req.query.sides as string) || 6;
    const rolls = rollDice(count, sides);
    const total = rolls.reduce((sum, roll) => sum + roll, 0);
    
    res.json({ rolls, total });
});

app.listen(PORT, '0.0.0.0', () => {
    console.log(`Server running on port ${PORT}`);
});

Explanation:

  • app.get('/roll', ...) defines a GET route that responds to GET requests at /roll.
  • req.query contains the query parameters from the URL.
  • parseInt() converts the string parameters to numbers.
  • res.json() sends a JSON response to the client.
  • The server listens on 0.0.0.0:3000 to accept connections from any network interface.

Running and Testing

Now it's time to see your work in action. First, make sure you have a script in your package.json to run TypeScript:

plaintext
Add a start script to package.json that runs ts-node src/index.ts

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

plaintext
npm start

Explanation:

  • ts-node compiles and runs TypeScript files directly without a separate build step.
  • The server listens on 0.0.0.0:3000, which means it accepts connections on all network interfaces on port 3000, which the platform exposes.

Once the server is running, open the platform's preview feature for port 3000 and test:

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

You should see a JSON response like:

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

This means you rolled 3 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 Express application with TypeScript using 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 Express 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