12 Exercise Task: API Routes in Next.js

Create an API route in Next.js that returns a list of books. Each book should have at least the following information: title, author, and publication year. The data can be static and does not need to be fetched from a database.

The API route should be accessible at the path /api/books. Ensure that the data is returned in JSON format.

Your task is to perform the following steps:

  1. Create a new Next.js project or use an existing one.

  2. Create a folder named pages in the root directory of your project if it doesn’t already exist.

  3. Inside the pages folder, create a subfolder named api.

  4. Inside this api folder, create a file named books.js. This will be your API route.

  5. Implement the code in the books.js file to return a list of books. Here is an example code you can use:

// pages/api/books.js

export default (req, res) => {
  const books = [
    { title: 'Book 1', author: 'Author 1', year: 2020 },
    { title: 'Book 2', author: 'Author 2', year: 2019 },
    { title: 'Book 3', author: 'Author 3', year: 2021 },
  ];

  res.status(200).json(books);
};
  1. Start your Next.js development server if it’s not already running by running the command npm run dev or yarn dev.

  2. Access the API route in your browser by visiting the URL http://localhost:3000/api/books. You should see the list of books in JSON format.

Your exercise task is to follow the steps mentioned above and ensure that your API route works correctly and returns the expected data. You can expand or modify the list of books as needed to create different test cases.

12.1 Exercise: Building a Frontend and Backend for a User Profile Display using Next.js API Routing

12.1.1 Objective:

Develop a Next.js application with a frontend component that displays user profiles. The backend (API route in Next.js) will provide the data for these profiles.

12.1.2 Task:

  1. Set up a Next.js project and create two main parts: index.js (Frontend) and api/users.js (Backend).
  2. In the backend (api/users.js), create an API route that returns a JSON array of user profiles. Each profile should contain a userId, name, and email.
  3. In the frontend (index.js), fetch data from the backend API route and display the list of user profiles.

12.1.3 Requirements: