Skip to main content

API

Next.js ships with API routes, which provide an easy solution to build your own API. In cella application, we also provide api that allow integrators handle custom actions that needed to do some business logic as well as 3rd party API calls.

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.

Creating new API endpoint

In pages/api folder create your API endpoint. For example the following API route pages/api/article.ts returns a json response with a status code of 200:

pages/api/article.ts
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}

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
} else {
// Handle any other HTTP method
}
}

Dynamic API Routes

API routes support dynamic routes, and follow the same file naming rules used for pages.

For example, the API route pages/api/article/update-quantity/[id].ts has the following code:

import type { NextApiRequest, NextApiResponse } from 'next';
import { GraphQLClient, gql } from 'graphql-request';

export default async (req: NextApiRequest, res: NextApiResponse) => {
const { id } = req.query;
const token = req.headers.cookie?.split('token=')[1].split(';')[0];
const requestHeader = {
authorization: `Bearer ${token}`
};
const graphqlRequestClient = new GraphQLClient(
process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT as string,
{
headers: requestHeader
}
);
// handle logic of calculating box quantity
...
res.status(200).json({ quantity: result.updateArticle.boxQuantity });
}

You can get id as requests query and can handle logic to calculate the box quantity and return it as json response.