Skip to main content

How to Create an SDK for Your FastAPI Application

This tutorial includes the following SDK languages and versions:

TypeScriptJavaPythonC#GoPHP

Any modern software development requires integration with APIs. 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 post we will explore how to seamlessly create an SDK for your FastAPI app using liblab SDK generator.

In order to auto-generate SDKs from a FastAPI server we need an OpenAPI file. The OpenAPI file contains API information like paths, params, security schemas, and other. FastAPI automatically generates OpenAPI file from your code, so you have all you need to build SDKs from this file using liblab.

Prerequisites

Steps

  1. Setting up an example Llama API
  2. Setting up the liblab CLI
  3. Generate the SDK

1. Setting up an example Llama API

First, let's install FastAPI by running pip install fastapi.

Next, we need to create a new directory for the project - mkdir -p llamapi.

FastAPI is very simple to develop, we only need one file, let’s create llamapi/main.py:

# llamapi/main.py
from fastapi import FastAPI

app = FastAPI()


# we can choose the SDK method name
# by changing the operation_id
@app.get("/llamas", operation_id="get_llamas")
async def get_llamas():
return {"content": ["Libby the llama", "Paka the alpaca"]}

We can run the api using fastapi dev main.py

You should see your api running on http://localhost:8000 if you have not changed any of the defaults.

The open-api spec, however, will be at http://localhost:8000/openapi.json

2. Setting up the liblab CLI

First, ensure you have the liblab CLI installed. If not, you can install it via npm:

npm install -g @liblab/cli

Once installed, you need to log in to your liblab account. Run the following command and follow the prompts to log in:

liblab login

After logging in, you can configure the CLI with your project. We want a new directory for the SDK, let's create one in the same directory as llamapi:

mkdir -p llamapi-sdk
cd llamapi-sdk
liblab init

This will generate a liblab.config.json.

Before we edit the generated json file, let’s download the API spec for which we will generate this SDK.

ℹ️ Usually we don’t need to download the API spec since we can point to a remote URL. However this URL must be publicly available, and our localhost server is not.

Go to http://localhost:8000/openapi.json and download the file to llamapi-sdk/openapi.json

Now let’s edit llamapi-sdk/liblab.config.json, and point the SDK generator to our OpenAPI spec file.

The final json should look something like this:

{
"sdkName": "llamapi-sdk",
"apiVersion": "1.0.0",
"apiName": "llamapi",
"specFilePath": "./openapi.json",
"languages": ["python"],
"auth": [],
"customizations": {
"includeOptionalSnippetParameters": true,
"devContainer": false,
"generateEnv": true,
"inferServiceNames": false,
"injectedModels": [],
"license": {
"type": "MIT"
},
"responseHeaders": false,
"retry": {
"enabled": true,
"maxAttempts": 3,
"retryDelay": 150
}
},
"languageOptions": {
"python": {
"alwaysInitializeOptionals": false,
"pypiPackageName": "",
"githubRepoName": "",
"ignoreFiles": [],
"sdkVersion": "1.0.0",
"liblabVersion": "2"
}
},
"publishing": {
"githubOrg": ""
}
}

3. Generate the SDK

Now that we have an OpenAPI spec file and the liblab CLI, it is time to generate our SDK.

Inside of llamapi-sdk execute the following command:

liblab build

The CLI will validate and notify us about any issues with the liblab.config.json or the openapi.json files. You might expect something like:

✓ No issues detected in the liblab config file.

Detected 5 potential issues with the spec:

⚠ OpenAPI "servers" must be present and non-empty array.
⚠ Info object must have "contact" object.
⚠ Info "description" must be present and non-empty string.
⚠ Operation "description" must be present and non-empty string.
⚠ Operation must have non-empty "tags" array.
Created /Users/stevan/Work/open-source/llamapi-sdk/output/api-schema-validation.json with the full linting results

? 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)

We can go ahead and confirm by typing Y.

Next we should see the build started and hopefully finished messages:

⠸ Building Python
✓ Python built
Successfully generated SDKs downloaded. You can find them inside the /Users/stevan/Work/open-source/llamapi-sdk/output folder
Successfully generated SDK's for Python ♡

If we go inside the output directory, we will see our SDK:

Generated SDK

Congratulations! You have successfully generated an SDK for your FastAPI app.

Conclusion

In conclusion, creating an SDK for your FastAPI application not only simplifies the development process for users but also enhances the accessibility and usability of your API. By following the steps outlined in this tutorial, you’ve learned how to utilize the liblab CLI to generate a robust SDK, ensuring your API can be easily integrated and utilized by other developers. Remember, a well-documented and user-friendly SDK can be a game-changer in how your API is adopted and valued in the developer community.

Make sure to read our guide on how to publish so users can download and use it.