Skip to main content

Automate SDK generation for Next.js APIs

Supported SDK languages:

TypeScript /
Javascript
Java /
Kotlin
PythonC#GoPHP

tip
  1. Before getting started make sure you have a liblab account and the liblab CLI installed.
  2. If you don't have an existing project but want to try out liblab then check out our standalone tutorials.

Providing an SDK for your API can significantly ease the development process for users, ensuring quicker integration and encouraging wider adoption due to the streamlined development experience.

In this doc you'll learn how to take your existing Next.js API and generate user-friendly SDKs for most major programming languages using the liblab SDK generator. After a short bit of setup you'll have a pipeline that will automatically generate SDKs for your API whenever you make changes.

Initializing the SDK

First, create a new directory to store your SDK. This directory should be separate from your existing project directory:

mkdir Next-js-sdk cd Next-js-sdk

And initialize your project to create a liblab.config.json file:

liblab init -y

Getting an OpenAPI Spec File

In order to auto-generate SDKs from a Next.js project, you need an OpenAPI Spec File. The OpenAPI specification is a standardized format that describes RESTful APIs, including endpoints, parameters, responses, and authentication methods.

Next.js doesn't generate OpenAPI specs natively, but you can create and serve them using the next-swagger-doc package.

This guide will walk you through the steps to use next-swagger-doc to generate the OpenAPI spec from your Next.js API.

Installation

To install the next-swagger-doc package, navigate to your Next.js API directory and run:

npm install next-swagger-doc

Setting Up OpenAPI Configuration

After installation, you'll need to create a configuration file for next-swagger-doc, which you'll use to specify metadata about your API. Create a swagger.js file within your lib directory:

mkdir -p lib
touch lib/swagger.js

Then configure the high level options of your API such as:

  • info: Define the API's title, description, version, and other metadata.
  • servers: Specify your API servers, such as production and development URLs.
  • security: Configure authentication mechanisms used by your API.
  • components: Add reusable objects like schemas and security schemes.
  • tags: Group endpoints under categories for better organization.
Beyond the Basics

You can use all properties defined in OpenAPI V3 to customize your OpenAPI spec.

The following code snippet shows a comprehensive configuration for the lib/swagger.js file:

swagger.js
import path from 'path';
import { createSwaggerSpec } from 'next-swagger-doc';

export const getSwaggerSpec = () => {
const spec = createSwaggerSpec({
apiFolder: path.join(process.cwd(), 'pages/api'),
definition: {
openapi: '3.0.0',
info: {
title: 'Greeting API',
version: '1.0.0',
description: 'A Next.js API for generating personalized greetings',
contact: {
name: 'API Support',
email: '[email protected]'
},
license: {
name: 'MIT',
url: 'https://opensource.org/licenses/MIT'
}
},
servers: [
{
url: 'http://localhost:3000',
description: 'Development server'
},
{
url: 'https://api.example.com',
description: 'Production server'
}
],
components: {
securitySchemes: {
apiKey: {
type: 'apiKey',
name: 'x-api-key',
in: 'header',
description: 'API key for authentication'
}
},
schemas: {
GreetingResponse: {
type: 'object',
properties: {
message: {
type: 'string',
description: 'The greeting message'
}
}
}
}
},
tags: [
{
name: 'Greetings',
description: 'Endpoints related to user greetings'
}
]
},
});
return spec;
};

Annotating API Routes with JSDoc

Take it one step at a time

You don't need to annotate every part of your API at once. You can annotate any number of routes, try out the rest of this guide, and return to the rest of your routes later.

To generate the best SDK and documentation possible for your SDK's users, you should provide additional metadata alongside the definitions of your endpoints which will be included in the generated OpenAPI spec.

You'll use JSDoc annotations to document these endpoints for your OpenAPI spec. When using JSDoc to add annotations, you can use all the properties available in OpenAPI. Here's a short list of the most important properties:

  • path: The endpoint's URL pattern (e.g., /api/greeting/{name}).
  • HTTP Method: The request method used (e.g., get).
  • operationId: A unique identifier for the operation (e.g., getGreeting).
  • summary and description: A brief summary and a detailed description of the endpoint's function.
  • tags: Categories to group related endpoints (e.g., Greetings).
  • parameters: Input values required by the endpoint (e.g., name as a path parameter).
  • responses: Possible responses, including status codes and schemas (e.g., 200 for a successful request).
  • security: Security mechanisms required for the endpoint.

The following code snippet shows how to define a comprehensive greeting endpoint:

pages/api/greeting.js
/**
* @swagger
* /api/greeting/{name}:
* get:
* operationId: getGreeting
* summary: Get a personalized greeting
* description: Returns a greeting message for the specified name.
* tags:
* - Greetings
* security:
* - apiKey: []
* parameters:
* - name: name
* in: path
* required: true
* schema:
* type: string
* example: World
* description: The name to greet
* responses:
* 200:
* description: Successful response
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/GreetingResponse'
* example:
* message: "Hello, World!"
* 400:
* description: Bad Request - Missing name parameter
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* description: Error message explaining the cause of the bad request
* example:
* error: "Missing name parameter"
*/
export default function handler(req, res) {
const { name } = req.query;

if (!name) {
return res.status(400).json({ error: "Missing name parameter" });
}

res.status(200).json({ message: `Hello, ${name}!` });
}

Serving the Spec

By default, next-swagger-doc does not expose the OpenAPI spec automatically. You must create a new route to serve the OpenAPI spec as a JSON file.

Server your spec by creating an endpoint like pages/api/openapi.json.js and defining the route as so:

pages/api/openapi.json.js
import { getSwaggerSpec } from '../../lib/swagger';

export default function handler(req, res) {
res.status(200).json(getSwaggerSpec());
}

Accessing the Spec

Now start your Next.js development server:

npm run dev

To view your OpenAPI spec, navigate to the /api/openapi.json endpoint on your server (e.g., http://localhost:3000/api/openapi.json).

Click to see the OpenAPI spec example for the greeting API.
{
"openapi": "3.0.0",
"info": {
"title": "Greeting API",
"version": "1.0.0",
"description": "A Next.js API for generating personalized greetings",
"contact": {
"name": "API Support",
"email": "[email protected]"
},
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
}
},
"servers": [
{
"url": "http://localhost:3000",
"description": "Development server"
},
{
"url": "https://api.example.com",
"description": "Production server"
}
],
"components": {
"securitySchemes": {
"apiKey": {
"type": "apiKey",
"name": "x-api-key",
"in": "header",
"description": "API key for authentication"
}
},
"schemas": {
"GreetingResponse": {
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "The greeting message"
}
}
}
}
},
"paths": {
"/api/greeting/{name}": {
"get": {
"operationId": "getGreeting",
"summary": "Get a personalized greeting",
"description": "Returns a greeting message for the specified name.",
"tags": [
"Greetings"
],
"security": [
{
"apiKey": []
}
],
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"schema": {
"type": "string",
"example": "World"
},
"description": "The name to greet"
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GreetingResponse"
},
"example": {
"message": "Hello, World!"
}
}
}
},
"400": {
"description": "Bad Request - Missing name parameter",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"error": {
"type": "string",
"description": "Error message explaining the cause of the bad request"
}
}
},
"example": {
"error": "Missing name parameter"
}
}
}
}
}
}
}
},
"tags": [
{
"name": "Greetings",
"description": "Endpoints related to user greetings"
}
]
}

Copy your spec

You're ready to proceed now that your openapi.json file has been generated. Save your openapi.json file to the liblab project directory you created during the initializing step. This is typically something like:

cd ../Next-js-sdk curl -o openapi.json http://localhost:3000/api/openapi.json

Configuring liblab

Now you'll need to make some minor updates to your liblab.config.json file in your Next-js-sdk folder:

  1. Point the specFilePath parameter to the location of your OpenAPI spec file (ex. ./openapi.json).
  2. Specify the baseUrl of your API. This is the URL that the SDK will use to make requests to your API.

The top of the file should then looks something like this:

{
"sdkName": "Next-js-sdk",
"apiVersion": "1.0.0",
"apiName": "Next-js-api",
"specFilePath": "./openapi.json",
"baseUrl": "http://localhost:PORT",
"languages": [
"go",
"java",
"python",
"typescript",
"csharp",
"php"
],
"auth": [
"bearer"
]
}
note

liblab's SDK generator supports many more advanced URL and environment configuration options than the basic configuration shown here.

Explore the configuration documentation to discover all the available settings and enhancements or review the SDK customization options for tailored adjustments.

Generate the SDK

info

During build you might see warnings about the OpenAPI spec. These are often minor issues that can be fixed later.

Now that you have an OpenAPI spec file and have finished setting the liblab.config.json file, it's time to generate our SDK:

liblab build -y

The CLI will validate the OpenAPI spec and notify you about any issues with it or the liblab.config.json.

The output will look something like this:

✓ No issues detected in the liblab config file.

No hooks found, SDKs will be generated without hooks.

⚠ Validation succeeded with warnings

Created /Users/username/projects/Next-js-sdk/output/api-schema-validation.json with the full linting results

Next you'll see the builds started and once they're done you'll see a message like this:

Your SDKs are being generated. Visit the liblab portal (https://app.liblab.com/apis/Next-js-sdk/builds/1234) to view more details on your build(s). ✓ C# built ✓ Go built ✓ Java built ✓ PHP built ✓ Python built ✓ TypeScript built ✓ Generate package-lock.json for TypeScript Successfully generated SDKs for Python, Java, Go, TypeScript, C#, PHP. ♡ You can find them inside: /Users/username/projects/Next-js-sdk/output

If we go inside the output directory, we will see a directory for each of our SDKs:

ls output/     api-schema-validation.json go php typescript     csharp java python

Try out your SDK

Environment Setup

The following instructions assume you have already set up the respective development environment for the language you are testing. If necessary refer to each language's official documentation before proceeding.

Learn more about the language versions liblab generated SDKs support.

note

The generated SDKs are intended to be deployed to package managers for end users. The instructions below to test your SDK locally will differ from user-facing instructions.

cd output/typescript/examples
npm run setup
npm run start

Next Steps

Now that you've packaged your SDKs you can learn how to integrate them with your CI/CD pipeline and publish them to their respective package manager repositories.

We currently have guides for: