Skip to main content

Automate SDK creation for Express 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 Express 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 Express-sdk cd Express-sdk

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

liblab init

Getting an OpenAPI Spec File

In order to auto-generate SDKs from an Express 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.

Installing JSDoc

You can generate OpenAPI Specs for your Express project using the swagger-jsdoc library. This library allows you to annotate your existing Express routes with OpenAPI comments in JSDoc format. The library then generates an OpenAPI spec file that can be used to generate SDKs for your API. Let's walk through the steps to do so.

First, navigate to your existing project directory and install the necessary packages:

npm install swagger-jsdoc

Configuring JSDoc

Next, add a configuration file named swaggerOptions.js to your project's root directory with the following content. This file will define the structure of the OpenAPI spec.

const swaggerJsDoc = require('swagger-jsdoc');

const swaggerOptions = {
definition: {
openapi: '3.1.0',
info: {
title: 'Express API',
version: '1.0.0',
description: 'A simple Express API',
},
servers: [
{
url: 'http://localhost:3000', // Set the path to your server
},
],
},
apis: ['./routes/*.js'], // Set the path to your route files
};

const swaggerSpec = swaggerJsDoc(swaggerOptions);

module.exports = swaggerSpec;

Now update the apis and servers section of swaggerOptions.js such that:

  1. The apis parameter points to the location of the files defining your endpoints. Typically this is your routes folder.
  2. Update the servers parameter to the url where your API is hosted. Typically during this stage you would set this to a url for local development. This URL can always be changed later and liblab offers many options for configuring your server URL environment.

Modifying Your Express App

In your main application file, normally named index.js or app.js, import and configure the Swagger middleware to serve the OpenAPI documentation. The following code snippet shows a configuration example where the fs library is used to save the generated OpenAPI file every times you start the application.

index.js / app.js
const express = require('express');
const swaggerSpec = require('./swaggerOptions');
const fs = require('fs');

const app = express();
const PORT = 3000;

// Middleware to parse JSON requests
app.use(express.json());

// ...The rest of your app.use() statements

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
// Save the OpenAPI spec file to the project root
fs.writeFileSync('./openapi.json', JSON.stringify(swaggerSpec, null, 2));
console.log('OpenAPI spec saved to openapi.json');
});

Annotating Your Routes

Take it one step at a time

You don't need to annotate every route at once. You can start with annotating a single route, or even just part of a route (ex. the 200 response) to get the hang of the annotations. liblab will only build routes for endpoints that you define here and are written to your openapi.json file.

Annotate your existing route files with OpenAPI comments in JSDoc. These annotations will be used by swagger-jsdoc to generate the OpenAPI spec. Typically they define:

  • The endpoint for the route.
  • The HTTP request methods accepted by the route (ie. GET, POST, PUT, etc.).
  • A human-readable summary of what the method returns.
  • A list of responses delineated by status code. Each response should contain a description and a content section describing the content returned.

Below is an example for a hypothetical route that exists at routes/api.js. It describes a single endpoint that receives a GET request and returns a HTTP 200 response with a JSON object (ie. application/json) containing a welcome message.

const express = require('express');
const router = express.Router();

// Root endpoint
/**
* @swagger
* /api:
* get:
* summary: Get the API home message
* responses:
* 200:
* description: A successful response
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
*/
router.get('/', (req, res) => {
res.json({ message: 'Welcome to the API!' });
});

// Export the router
module.exports = router;
Swagger's Helpful Docs

Check Swagger's OpenAPI documentation for a summary on common annotation options.

After starting the server, you should see the following messages in your terminal:

Server is running on http://localhost:3000
OpenAPI spec saved to openapi.json

Copy Your Spec

Now that your openapi.json file is generated copy it to the Express-sdk folder that you setup during the Initialization step. This is typically something like:

cp openapi.json ../Express-sdk

Configuring liblab

Now you'll need to make some minor updates to your liblab.config.json file in your Express-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": "Express-sdk",
"apiVersion": "1.0.0",
"apiName": "Express-api",
"specFilePath": "./openapi.json",
"baseUrl": "http://localhost:PORT",
"languages": [
"go",
"java",
"python",
"typescript",
"csharp"
],
"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

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/Express-sdk/output/api-schema-validation.json with the full linting results

Detected 8 potential issues with the spec:

⚠ Info object must have "contact" object. ⚠ Info "description" must be present and non-empty string. ⚠ Operation "description" must be present and non-empty string. (3 occurrences) ⚠ Operation tags must be defined in global tags. (3 occurrences) ? It is important to fix your spec before continuing with a build. Not fixing the spec may yield a subpar SDK and documentation. Would you like to attempt to build the SDK anyway? (Y/n)

You can go ahead and confirm by typing Y.

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

Ignoring the spec errors and attempting to build with the spec

Your SDKs are being generated. Visit the liblab portal (https://app.liblab.com/apis/Express-sdk/builds/1234) to view more details on your build(s). ✓ C# built ✓ Go built ✓ Java built ✓ Python built ✓ TypeScript built ✓ Generate package-lock.json for TypeScript Successfully generated SDKs for Python, Java, Go, TypeScript, C#. ♡ You can find them inside: /Users/username/projects/Express-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 python csharp java typescript

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 Continuous Integration / Continuous Delivery (CI/CD) pipeline. CI/CD integration will ensure that your SDKs automatically update and publish to their respective package manager repositories with every release.

We currently have guides for: