Automate SDK creation for Django 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 Django 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 Django-sdk
cd Django-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 a Django project you need an OpenAPI spec file. The OpenAPI Spec file contains information that describes your API like servers, paths, operations, parameters, responses, and security schemas.
This guide will walk you through the step by step process of creating your OpenAPI spec file by installing drf-spectacular, configuring it, and annotating your project.
Installing drf-spectacular
To install drf-spectacular
, navigate to your project directory and run:
pip install drf-spectacular
Configuring drf-spectacular
Once drf-spectacular
is installed, you must configure it in your Django project. Open your Django project's settings.py
file and add drf_spectacular
to the INSTALLED_APPS
list:
INSTALLED_APPS = [
# ...
'drf_spectacular', # Add drf_spectacular to your project
]
In the same settings.py
file, configure Django REST Framework to use drf_spectacular
as the default OpenAPI schema generator:
REST_FRAMEWORK = {
# ...
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
# ...
}
The basic API configurations are also specified in your settings.py
file, configuring the drf-spectacular
:
# ...
SPECTACULAR_SETTINGS = {
'TITLE': 'Your API Title',
'DESCRIPTION': 'Your API Description',
'VERSION': '1.0.0', # Update as needed
}
# ...
To serve the OpenAPI spec, import SpectacularAPIView
from drf_spectacular.views
and add the following URL pattern to your project's urls.py
file:
from drf_spectacular.views import SpectacularAPIView
urlpatterns = [
# ...
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
# ...
]
Annotating Your Project
In most cases your Django 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.
To annotate your API views you can use only the @extend_schema
decorator from drf-spectacular
. This lets you add descriptions, response examples, and custom parameters to your API documentation.
drf-spectacular
provides a drop-in OpenApiViewExtension
class. It won't change the behavior of your views. It only provides more information to drf-spectacular
for generating the OpenAPI Spec.
You can import the following utilities from drf_spectacular.utils
to annotate your API views:
extend_schema
: Defines metadata for your API endpoint, such as descriptions, expected parameters, and response types.OpenApiParameter
: Allows you to specify request parameters, their location (e.g., query, path, or header), data types, and example values.OpenApiExample
: Provides structured example values for parameters, making it easier for API consumers to understand expected inputs.OpenApiResponse
: Describes possible responses, including HTTP status codes, response structures, and example outputs.
Here's an example of how you can use these utilities to annotate a class-based view that handles GET requests. This view expects a name
parameter in the URL path and responds with a greeting message.
# ...
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample, OpenApiResponse
class HelloView(APIView):
# ...
@extend_schema(
description="Send a friendly greeting to a user by name.",
parameters=[
OpenApiParameter(
name="name",
type=str,
location=OpenApiParameter.PATH,
description="The name to greet.",
examples=[
OpenApiExample(
"Example 1",
value="Alice",
summary="Greet Alice",
description="An example of greeting someone named Alice."
),
],
),
],
responses={
200: OpenApiResponse(
description="Successful Response",
response={
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "Hello, Alice!"
}
}
}
),
},
)
def get(self, request, name):
return Response({"message": f"Hello, {name}!"}, status=status.HTTP_200_OK)
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 an understanding of annotations.
drf-spectacular
has documentation for further customizing your OpenAPI Spec. Check it out to learn how to add annotations such as custom response headers, authentication schemes, and more.
If you're interested in learning more about OpenAPI Specifications in general then Swagger's OpenAPI documentation is a great starting point for common annotations.
Complete Example
Putting the above steps together produces a complete example of generating an Openapi Spec in a Django Rest Framework project using drf-spectacular
.
- settings.py
- urls.py
- app/views.py
# ...
INSTALLED_APPS = [
# ...
'rest_framework',
'app',
'drf_spectacular',
]
REST_FRAMEWORK = {
# ...
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
SPECTACULAR_SETTINGS = {
'TITLE': 'Hello API',
'DESCRIPTION': 'A simple API to greet users by name.',
'VERSION': '1.0.0',
}
# ...
# ...
from drf_spectacular.views import SpectacularAPIView
urlpatterns = [
# ...
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
]
#...
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiExample, OpenApiResponse
class HelloView(APIView):
@extend_schema(
description="Send a friendly greeting to a user by name.",
parameters=[
OpenApiParameter(
name="name",
type=str,
location=OpenApiParameter.PATH,
description="The name to greet.",
examples=[
OpenApiExample(
"Example 1",
value="Alice",
summary="Greet Alice",
description="An example of greeting someone named Alice."
),
OpenApiExample(
"Example 2",
value="Bob",
summary="Greet Bob",
description="An example of greeting someone named Bob."
),
],
),
],
responses={
200: OpenApiResponse(
description="Successful Response",
response={
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "Hello, Alice!"
}
}
},
examples=[
OpenApiExample(
"Example 1",
value={"message": "Hello, Alice!"},
summary="Greet Alice",
description="A greeting message for Alice."
),
OpenApiExample(
"Example 2",
value={"message": "Hello, Bob!"},
summary="Greet Bob",
description="A greeting message for Bob."
),
]
),
},
)
def get(self, request, name):
return Response({"message": f"Hello, {name}!"}, status=status.HTTP_200_OK)
Click to see the example OpenAPI spec
{
"openapi": "3.0.3",
"info": {
"title": "Hello API",
"version": "1.0.0",
"description": "A simple API to greet users by name."
},
"paths": {
"/hello/{name}/": {
"get": {
"operationId": "hello_retrieve",
"description": "Send a friendly greeting to a user by name.",
"parameters": [
{
"in": "path",
"name": "name",
"schema": {
"type": "string"
},
"description": "The name to greet.",
"required": true,
"examples": {
"Example1": {
"value": "Alice",
"summary": "Greet Alice",
"description": "An example of greeting someone named Alice."
},
"Example2": {
"value": "Bob",
"summary": "Greet Bob",
"description": "An example of greeting someone named Bob."
}
}
}
],
"tags": [
"hello"
],
"security": [
{
"cookieAuth": []
},
{
"basicAuth": []
},
{}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string",
"example": "Hello, Alice!"
}
}
},
"examples": {
"Example1": {
"value": {
"message": "Hello, Alice!"
},
"summary": "Greet Alice",
"description": "A greeting message for Alice."
},
"Example2": {
"value": {
"message": "Hello, Bob!"
},
"summary": "Greet Bob",
"description": "A greeting message for Bob."
}
}
}
},
"description": "Successful Response"
}
}
}
}
},
"components": {
"securitySchemes": {
"basicAuth": {
"type": "http",
"scheme": "basic"
},
"cookieAuth": {
"type": "apiKey",
"in": "cookie",
"name": "sessionid"
}
}
}
}
Copy Your Spec
Next you'll need to obtain your OpenAPI spec file which you can do by starting your Django server:
python manage.py runserver
Then in another terminal copy your spec to your sdk project directory:
cd ../Django-sdk
curl -o openapi.json http://localhost:8000/api/schema/?format=json
It's also possible to generate the OpenAPI spec from your terminal with python manage.py spectacular --file openapi.json
.
Configuring liblab
Now you'll need to make some minor updates to your liblab.config.json
file in your Django-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": "Django-sdk",
"apiVersion": "1.0.0",
"apiName": "Django-api",
"specFilePath": "./openapi.json",
"baseUrl": "http://localhost:PORT",
"languages": [
"go",
"java",
"python",
"typescript",
"csharp"
],
"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
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/Django-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/Django-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/Django-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
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: