How to add API routes?
Adding the API routes in Next.js is simple. We need to add the javascript file under the api folder.
Let's say we need an api that returns the list of users. To accomplish this, create a getuser.js file under the api directory.
Add the following code:
function getUsers(req, res) {
const users = [
{
id: 1,
name: 'Michael Foo',
email: 'michael@foo.com'
},
{
id: 2,
name: 'John Cena',
email: 'john@example.com'
},
{
id: 3,
name: 'Zoho S',
email: 'zoho@example.com'
}
];
res.status(200).json({ users: users })
}
export default getUsers;
Visit http://localhost:3000/api/getuser
And you see the JSON data in the browser.
Dynamic API Routes
What we have learned so far are the static routes that return the JSON data. Sometimes, it's required to pass the dynamic variable or parameters (in the URL) and then get the data according to the variable. If we want to get the data for the individual user, we need to pass a dynamic variable (let's say id) in the URL and, the backend returns the data based on the id variable.
Create a new folder 'user' under the api and create [userId].js under the user folder.
Add the following code to the new file:
const users = [
{
id: 1,
name: 'Michael Foo',
email: 'michael@foo.com'
},
{
id: 2,
name: 'John Cena',
email: 'john@example.com'
},
{
id: 3,
name: 'Zoho S',
email: 'zoho@example.com'
}
];
function getUserDetails(req, res) {
const userId = req.query.userId
const userDetails = users.filter( user => user.id === Number(userId) )
res.status(200).json({ users: userDetails })
}
export default getUserDetails;
Go to the browser and visit
http://localhost:3000/api/user/2. You will see the details of the user having id equals 2.
In the above example, we created (copied from earlier instances) a user object. We return the response to the browser where user id equals 2.
One still can argue, we didn't use the database to get the user information. How can we say that it's a Full Stack Framework? Right in this article, we haven't covered the database. This article aims to get an understanding of the api routes in Next.js. We'll cover the database in the following article.
- Category
- Perl 6
- Python 0
- Data Science 1
- Data Analysis 4
- Machine Learning 6
- Mojolicious 10
- Ansible 1
- Nextjs 22