1. Set Up a Database Connection

Set up a new Express project with mysql2 and create a connection pool to your MySQL database. Use environment variables for your database credentials.

Create the following files:

  • .env with your database configuration and port
  • database.ts with connection pool setup
  • index.ts with basic Express setup

Test your connection by adding a simple endpoint that returns Connected to database when the connection works.

2. Build a Restaurants API

Apply what you learned to a different dataset. Create a restaurants table and build API endpoints for it.

Step 1: Create the restaurants table

CREATE TABLE restaurants (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    cuisine_type VARCHAR(50) NOT NULL,
    rating DECIMAL(2,1)
);

INSERT INTO restaurants (name, cuisine_type, rating) VALUES
('Pizza Palace', 'Italian', 4.2),
('Sushi House', 'Japanese', 4.7),
('Burger Joint', 'American', 3.8),
('Taco Bell', 'Mexican', 3.5),
('French Bistro', 'French', 4.9);

Step 2: Build the API endpoints

  1. Get all restaurants: GET /restaurants
  2. Get single restaurant: GET /restaurants/:id

Use the same patterns from the lesson: parameterised queries and error handling.

3. Add Pagination to Restaurants

Add more restaurants to the table and enhance your restaurants API by adding pagination support:

  • Add page and limit query parameters to GET /restaurants
  • Use default values: page 1, limit 10
  • Test with different page sizes and page numbers

4. Test Your Restaurants API

Test your restaurants endpoints thoroughly.

For GET /restaurants:

  • Test with no parameters (should use defaults)
  • Test pagination: /restaurants?page=2&limit=2
  • Test with different limits: /restaurants?limit=3

For GET /restaurants/:id:

  • Valid restaurant ID that exists
  • Restaurant ID that doesn’t exist (should return 404)
  • Invalid ID formats like letters or negative numbers

Example endpoints to test:

  • GET /restaurants
  • GET /restaurants?page=2&limit=2
  • GET /restaurants/2
  • GET /restaurants/-999
  • GET /restaurants/abc
Tags: