Creating your first API endpoint in Next.js

Tutorial 2 of 5

1. Introduction

In this tutorial, we will learn how to create your first API endpoint in Next.js. API endpoints are paths or URLs where API (Application Programming Interface) can be accessed by clients over HTTP.

By the end of this tutorial, you will be able to:
- Understand the basics of creating an API endpoint in Next.js
- Handle incoming HTTP requests and send responses

Prerequisites:
- Basic knowledge of JavaScript and Node.js
- Next.js installed on your local machine

2. Step-by-Step Guide

Next.js provides an integrated server-side solution, allowing us to create API routes in our Next.js app. These routes are server-side and do not add to your client-side JavaScript bundle size.

To create an API route, we create a file in the pages/api directory. The filename will be the API endpoint.

Steps to create an API endpoint

  1. Create a new file inside the pages/api directory. The name of the file will be the API endpoint. For example, hello.js will be accessed at http://localhost:3000/api/hello.
  2. Export a function that handles a request and a response object. The function can be async and can contain server-side code.

Handling Request and Response

  • req: An instance of http.IncomingMessage, plus some pre-built middlewares
  • res: An instance of http.ServerResponse, plus some helper functions

3. Code Examples

Here is a simple example of an API endpoint that returns a JSON response:

// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ text: 'Hello' })
}
  • export default function handler(req, res) { ... }: This creates an API route function. The function accepts two arguments: a request (req) and a response (res).
  • res.status(200).json({ text: 'Hello' }): This sends a response with a status code of 200 (OK) and the JSON response { text: 'Hello' }.

You can access this API endpoint at http://localhost:3000/api/hello.

4. Summary

In this tutorial, we have:
- Learned how to create an API endpoint in Next.js
- Learned how to handle requests and send responses from an API endpoint

Next steps:
- Learn how to connect to a database in your Next.js API routes
- Learn how to use middlewares in your API routes

Additional resources:
- Next.js API routes documentation

5. Practice Exercises

  1. Create an API endpoint at /api/goodbye that sends a JSON response { text: 'Goodbye' }.
  2. Create an API endpoint at /api/user that sends a JSON response { name: 'John Doe', email: 'john.doe@example.com' }.

Solutions:
1.

// pages/api/goodbye.js
export default function handler(req, res) {
  res.status(200).json({ text: 'Goodbye' })
}
// pages/api/user.js
export default function handler(req, res) {
  res.status(200).json({ name: 'John Doe', email: 'john.doe@example.com' })
}

Tips:
- Experiment with different response status codes and see how your API behaves.
- Try creating an API route that accepts query parameters.