Building a RESTful API with Next.js

Building a RESTful API with Next.js
Next.js is a powerful framework for building React applications, and it's also well-suited for creating server-side rendered APIs. In this article, we'll explore how to create a RESTful API using Next.js, covering various CRUD (Create, Read, Update, Delete) operations and request validation using Zod.
Building a RESTful API with Next JS

1. Getting a Collection of Objects

To fetch a collection of objects, you can create an API route in Next.js. Here's a simple example:
// pages/api/objects.js

export default function handler(req, res) {
  // Fetch objects from database or external API
  const objects = [{ id: 1, name: 'Object 1' }, { id: 2, name: 'Object 2' }];
  
  res.status(200).json(objects);
}
  

2. Getting a Single Object

To retrieve a single object, you can modify the API route to accept an ID parameter:
// pages/api/objects/[id].js

export default function handler(req, res) {
  const { id } = req.query;
  // Fetch object by ID from database or external API
  const object = { id, name: `Object ${id}` };
  
  res.status(200).json(object);
}
  

3. Creating an Object

For creating an object, you can use a POST request:
// pages/api/objects.js

export default function handler(req, res) {
  if (req.method === 'POST') {
    // Logic to create object
    res.status(201).json({ message: 'Object created successfully' });
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} not allowed`);
  }
}
  

4. Updating an Object

To update an object, you can use a PUT or PATCH request:
// pages/api/objects/[id].js

export default function handler(req, res) {
  if (req.method === 'PUT' || req.method === 'PATCH') {
    const { id } = req.query;
    // Logic to update object with ID
    res.status(200).json({ message: `Object ${id} updated successfully` });
  } else {
    res.setHeader('Allow', ['PUT', 'PATCH']);
    res.status(405).end(`Method ${req.method} not allowed`);
  }
}  
  

5. Deleting an Object

For deleting an object, you can use a DELETE request:
// pages/api/objects/[id].js

export default function handler(req, res) {
  if (req.method === 'DELETE') {
    const { id } = req.query;
    // Logic to delete object with ID
    res.status(200).json({ message: `Object ${id} deleted successfully` });
  } else {
    res.setHeader('Allow', ['DELETE']);
    res.status(405).end(`Method ${req.method} not allowed`);
  }
}
  

6. Validating Requests with Zod

Zod is a TypeScript-first schema declaration and validation library. You can use it to validate incoming requests:
import { z } from 'zod';

const objectSchema = z.object({
  name: z.string().min(3).max(50),
  // Define other properties here
});

export default function handler(req, res) {
  try {
    const { error, value } = objectSchema.parse(req.body);
    if (error) throw error;

    // Logic to handle valid request
    res.status(200).json({ message: 'Request validated successfully' });
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
}  
  

7. Exercise - Building Products API

Now that you've learned the basics, try building a Products API using Next.js. Implement endpoints for getting all products, getting a single product, creating a product, updating a product, and deleting a product. Don't forget to add request validation using Zod for creating and updating endpoints.

In conclusion, Next.js provides a robust platform for building RESTful APIs with ease. With its flexibility and powerful features, you can create APIs to serve various client-side applications efficiently.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.