Automate SDK generation for NestJS APIs
Supported SDK languages:
TypeScript / Javascript | Java / Kotlin | Python | C# | Go | PHP |
---|---|---|---|---|---|
✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
- Before getting started make sure you have a liblab account and the liblab CLI installed.
- 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 NestJS 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 NestJS-sdk
cd NestJS-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 NestJS project you need an OpenAPI Spec File. The OpenAPI file contains information that describes your API like servers, paths, operations, parameters, responses, and security schemas.
To get the OpenAPI spec file from your NestJS project you'll need to do the following:
This guide will walk you through the step-by-step process of creating your OpenAPI spec file using NestJS, configuring it, and annotating your project to generate a comprehensive OpenAPI specification.
Installing @nestjs/swagger
To generate the OpenAPI spec file, you need to install the @nestjs/swagger
package. Navigate to your project directory and run:
npm install @nestjs/swagger
Configuring @nestjs/swagger
After installing @nestjs/swagger
you need to integrate it into your NestJS application to generate the OpenAPI spec by creating a new DocumentBuilder
and providing a few configuration options:
- setTitle: The title of your API.
- setDescription: A description of your API.
- setVersion: The version of your API.
- addTag: Adds a tag for grouping related endpoints.
Here's an example of a basic configuration:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Configure OpenAPI spec
const config = new DocumentBuilder()
.setTitle('Hello API') // The title of your API
.setDescription('A simple API to greet users') // A description of your API
.setVersion('1.0') // The version of your API
.addTag('hello') // Add a tag for grouping endpoints
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document); // Serve the OpenAPI spec at /api-json
await app.listen(3000);
}
bootstrap();
Annotating Your Project
In most cases your NestJS project will now be able to produce an OpenAPI spec that you can use to automatically generate SDKs and Documentation for your API and you could jump ahead to the next step of copying your spec. However the generated SDK may be missing important annotations such as descriptions of endpoints, possible responses, parameters, and example values.
nestjs/swagger
uses decorators to annotate your API endpoints, which are then used to generate the OpenAPI spec. Some of the key decorators you can use to annotate your API include:
ApiTags('hello')
: Groups all endpoints in this controller under the hello tag in the OpenAPI spec.@ApiOperation({ summary, description })
: Adds a summary and description to the endpoint.@ApiParam({ name, type, description, required, example })
: Describes a path parameter, including its name, type, description, and example value.@ApiResponse({ status, description, schema })
: Describes the response, including its status code, description, and schema.
You don't need to annotate every view at once. You can start with annotating a single view, or even just part of it (e.g., the 200
response) to get the hang of the annotations.
Here's an example of a simple GET endpoint /hello/{name}
that accepts a name
parameter in the URL path and returns a greeting message:
import { Controller, Get, Param } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
@ApiTags('hello') // Groups endpoints under the "hello" tag
@Controller('hello')
export class HelloController {
@Get(':name') // Defines the GET endpoint /hello/{name}
@ApiOperation({
summary: 'Get a greeting message',
description: 'Returns a greeting message for the given name.',
})
@ApiParam({
name: 'name',
type: String,
description: 'The name of the person to greet',
required: true,
example: 'John',
})
@ApiResponse({
status: 200,
description: 'Successfully returned a greeting',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
description: 'The greeting message',
example: 'Hello John',
},
},
},
})
getHello(@Param('name') name: string): { message: string } {
return { message: `Hello ${name}` };
}
}
@nestjs/swagger
decorator documentation covers all the options available to annotate your API. Check it out to dive deeper into customizing your API.
If you're interested in learning more about OpenAPI specs in general, then Swagger's OpenAPI documentation is a great starting point for common annotations.
Complete Example
Here's the complete example of a NestJS application with annotations for generating the OpenAPI spec:
- Main
- Controller
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const config = new DocumentBuilder()
.setTitle('Hello API')
.setDescription('A simple API to greet users') your API
.setVersion('1.0')
.addTag('hello')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
}
bootstrap();
import { Controller, Get, Param } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
@ApiTags('hello') // Groups endpoints under the "hello" tag
@Controller('hello')
export class HelloController {
@Get(':name') // Defines the GET endpoint /hello/{name}
@ApiOperation({
summary: 'Get a greeting message',
description: 'Returns a greeting message for the given name.',
})
@ApiParam({
name: 'name',
type: String,
description: 'The name of the person to greet',
required: true,
example: 'John',
})
@ApiResponse({
status: 200,
description: 'Successfully returned a greeting',
schema: {
type: 'object',
properties: {
message: {
type: 'string',
description: 'The greeting message',
example: 'Hello John',
},
},
},
})
getHello(@Param('name') name: string): { message: string } {
return { message: `Hello ${name}` };
}
}
Click to see the OpenAPI spec example
{
"openapi": "3.0.0",
"paths": {
"/": {
"get": {
"operationId": "AppController_getHello",
"parameters": [],
"responses": {
"200": {
"description": ""
}
},
"tags": [
"App"
]
}
},
"/hello/{name}": {
"get": {
"operationId": "HelloController_getHello",
"parameters": [
{
"name": "name",
"required": true,
"in": "path",
"description": "The name of the user",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Returns a greeting message"
}
},
"summary": "Say hello to a user",
"tags": [
"hello"
]
}
}
},
"info": {
"title": "Hello API",
"description": "A simple API to greet users",
"version": "1.0",
"contact": {}
},
"tags": [
{
"name": "hello",
"description": ""
}
],
"servers": [],
"components": {
"schemas": {}
}
}
Viewing the OpenAPI Spec
Once your NestJS application is running, you can access the OpenAPI spec by navigating to the /api-json
endpoint (e.g., http://localhost:3000/api-json
). This will return the OpenAPI specification in JSON format.
Copy Your Spec
Now that your openapi.json
file is generated, you're ready to proceed. Save your openapi.json
file to the liblab project directory you created during the initializing step. This is typically something like:
cd ../NestJS-sdk
curl -o openapi.json http://localhost:3000/api-json
Configuring liblab
Now you'll need to make some minor updates to your liblab.config.json
file in your NestJS-sdk folder:
- Point the
specFilePath
parameter to the location of your OpenAPI spec file (ex../openapi.json
). - 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": "NestJS-sdk",
"apiVersion": "1.0.0",
"apiName": "NestJS-api",
"specFilePath": "./openapi.json",
"baseUrl": "http://localhost:PORT",
"languages": [
"go",
"java",
"python",
"typescript",
"csharp",
"php"
],
"auth": [
"bearer"
]
}
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
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/NestJS-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/NestJS-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/NestJS-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
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.
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.
- TypeScript / JavaScript
- Python
- Java
- C#
cd output/typescript/examples
npm run setup
npm run start
cd output/python/examples
chmod +x install.sh
./install.sh
source .venv/bin/activate
python3 sample.py
cd output/java/example
chmod +x run.sh
./run.sh
cd output/csharp/Example
dotnet run --framework net9.0
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: