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:
Create a new Next.js project or use an existing one.
Create a folder named pages
in the root directory of
your project if it doesn’t already exist.
Inside the pages
folder, create a subfolder named
api
.
Inside this api
folder, create a file named
books.js
. This will be your API route.
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 },
{ ;
]
.status(200).json(books);
res; }
Start your Next.js development server if it’s not already running
by running the command npm run dev
or
yarn dev
.
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.
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.
index.js
(Frontend) and api/users.js
(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
.index.js
), fetch data from the backend
API route and display the list of user profiles.