Adding New Routes

In this lesson, we'll be adding a few new routes and return mock data as responses.

We'll cover the following...

Get all your books

Let’s go ahead and make our mock data. We’ll use an array of JSON objects to define a list of books.

export interface IBook {
    id: string;
    name: string;
    author: string;
    genre: string;   
}

Go ahead and open up books.ts. You should notice many new changes. Let’s start at the top.

  • See the import statement mention types.ts in line 1? Open the file.

  • We’ve defined an interface, IBook, in line 1, with the basic shape of the data pertaining to a single book. It has the attributes of name, author, id, and genre. In essence, we have defined a custom type, which we can use to define our data.

  • Switch back to books.ts and you’ll notice an array of JSON object books on line 3, which is of type IBook[]- i.e., an array of our custom type. Each book has an id, name , author, and genre.

  • Scrolling down, you’ll find our old getBooks method in line 42. Now, instead of “Hello World”, we’re returning to a JSON object with two attributes: success, which will be true, and data, which has the value of our books array.

  • Now, if you run your app and make a GET request to the URL with /api/v1/books appended to it, you’ll get the following:

Press + to interact
{
"success": true,
"data": [
{
"id": "1",
"name": "The Great Gatsby",
"author": "F.Scott Fitzgerald",
"genre": "fiction"
},
{
"id": "2",
"name": "Little Women",
"author": "Louisa May Alcott",
"genre": "fiction"
},
{
"id": "3",
"name": "Pride and Prejudice",
"author": "Jane Austen",
"genre": "romance"
},
{
"id": "4",
"name": "1984",
"author": "George Orwell",
"genre": "sci-fi"
},
{
"id": "5",
"name": "Moby Dick",
"author": "Herman Melville",
"genre": "epic"
},
{
"id": "6",
"name": "Animal Farm",
"author": "George Orwell",
"genre": "allegory"
}
],
}

There you go! Now ...