Skip to main content

700. API Routes

  • API routes allow you to create RESTful endpoints as part of your Next.js application folder structure
  • Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.
  • How to handle, API requests
    • GET,POST and DELETE requests
    • Dynamic API routes
    • Catch all API routes
  • Within the api folder, you can define all the APIs for your application

API Basic

export default function handler(req, res) {
return res.status(200).json({name: 'Hello Mexico'})
}
  • To handle different HTTP methods in an API route, you can use req.method in your request handler, like so:
export default function handler(req, res) {
if (req.method === 'POST') {
// Process a POST request
//const blog = req.body.blogs;
} else {
// Handle any other HTTP method
}
}
  • To handle dynamic api routes,
//[blogid].js
import {Blogs} from "../../../data/blogs";

export default function handler(req, res) {
const {blogid} = req.query;
if (req.method === 'GET') {
const blog = Blogs.filter(blog => blog.id === parseInt(blogid));
res.status(200).json(blog);
}else if(req.method === 'DELETE'){
const index = Blogs.findIndex(blog => blog.id === parseInt(blogid));
Blogs.splice(index, 1);
res.status(200);
}
}
  • Catch all api routes
//[...params].js
export default function handler(req,res){
const params = req.query.params
console.log(params); //or
return res.status(200).json(params)
}

Don't call your own next API routes for pre-rendering content, either directly access the data(DB, json file, headless CMS), unless using consistent api for all platforms.