Building a Simple API on Mock Data

Intro

In this lesson, you'll learn how to build a simple API using Express.js and mock data. We'll cover setting up an Express.js server, creating mock data, writing endpoints, and retrieving data.

What you'll learn

By the end of this lesson, you will:

  • Set up an Express.js server
  • Create mock data arrays
  • Write POST endpoints for adding data
  • Write GET endpoints for retrieving data
  • Start your server

Step 1: Setting up Express.js

Here we'll learn to set up an Express.js server. This is crucial as it forms the backbone of our API, giving us a robust platform to build on.

const express = require('express'); // Import Express.js library

const app = express(); // Create an instance of Express
const PORT = 3000; // Port where the server will listen

app.use(express.json()); // Middleware to parse JSON request bodies

To set up an Express.js server, we first need to import the Express library using require('express'). Then, we create an instance of the Express application by calling express(). We define a port number where the server will be listening for requests; in this case, it’s set to 3000. Additionally, we use a middleware function express.json() which allows our server to parse JSON data in the request bodies. This setup is fundamental as it creates the environment where our API can live and function.

Step 2: Creating Mock Data

Let's move to creating mock data arrays. We do this to simulate a real-world scenario and not use a complex database. This is for learning purposes, and in real-life scenarios, you'll always be using real databases.

// Mock data
const users = [
    { id: 1, name: 'John Doe', email: 'john@example.com' },
    { id: 2, name: 'Jane Doe', email: 'jane@example.com' },
    { id: 3, name: 'Sam Smith', email: 'sam@example.com' },
];

const posts = [
    { id: 1, title: 'First Post', content: 'This is the first post', userId: 1 },
    { id: 2, title: 'Second Post', content: 'This is the second post', userId: 2 },
];

const categories = [
    { id: 1, name: 'Tech', posts: [1] },
    { id: 2, name: 'Lifestyle', posts: [2] },
];

Instead of diving into database management, we create mock data to simulate real data. This step involves defining arrays for users, posts, and categories. These arrays hold objects that represent typical data entities you would encounter in a real-world situation. For users, each object contains an id, name, and email. The posts array includes id, title, content, and userId (to link posts to specific users). Lastly, the categories array comprises id, name, and posts (an array of post IDs under that category). Using mock data keeps things simple and focuses on learning the core concepts.

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