read24 - Server: Stubbing API

July 3, 2020

Roger Ngo

The data model objects have been defined, and now I will need to create the API endpoints. I should be able to test these through the web browser if the HTTP method is GET, but since most are POST, testing will be done through Postman. It can be found here:

As a quick reminder, the API endpoints have been defined in the Introduction document, but I will display them here again for reference:

POST /login
GET /book/search/title/bookTitle
GET /book/search/author/authorName
POST /quiz/book
POST /quiz/book/question
POST /quiz/book/rate
POST /student/report

Judging from the above, it seems like we will need 4 route files. The login, book,quiz, and student routes.

All routes will be placed in the /src/routes folder. For example, the book route implementation will be created and implemented under /src/routes/book.ts. Since I am just interested in providing the routes for now, I will stub the implementation as pass-throughs.

Here is the implementation for now:

import { IRouter } from "express";

export function mountBook(app: IRouter) {
    app.get('/book/search/title/:bookTitle', (req, res) => {
        res.status(200).send(`bookTitle: ${req.params.bookTitle}`);

    app.get('/book/search/author/:authorName', (req, res) => {
        res.status(200).send(`authorName: ${req.params.authorName}`);

Then modify index.ts to include the book routes by calling mountBook with app as the parameter:

import * as express from 'express';
import {mountBook} from './routes/book';

const app = express();

// ... stuff here


// ... stuff here

Build, run, and test the /book/search/title/:bookTitle route in Postman:

Postman GET test

Looks good. Now I can stub all routes the same way.

One consideration I have made is that I am assuming all request body content for POST requests come in the form of JSON. Therefore, I need to use bodyParser in order to parse out the HTTP request body.

// .. stuff here
import * as bodyParser from 'body-parser';

const app = express();


// ... stuff here

Now, suppose I have /quiz/book/rate just return back the body which I had sent as the response. I should get back the JSON.

Postman POST test