Skip to main content

24 posts tagged with "SDK"

View All Tags
← Back to the liblab blog

TL;DR - we've created a new tutorial that shows you how to quickly add retrieval augmented generation (RAG) to your AI app using autogenerated SDKs that wrap your internal APIs. Check it out on the liblab developer portal.

Everyone has heard of ChatGPT, the popular large language model (LLM) that can generate human like text, answering any question you may have with a certain degree of correctness. However, the biggest problem with these large language models is that they only have a limited amount of 'knowledge' to draw on - they are trained using data from the internet up to a particular date, and that is it.

For example, if you ask an LLM what todays date is, or what the weather is like in a particular city, it will not be able to answer you - it just doesn't have that data.

This lack of data also limits an LLMs ability to answer questions, or reason, based off your own data. For example, if you have a database of customer reviews, and you want to ask the LLM a question about the reviews, it will not be able to answer you as it simply doesn't have access to that data. This is where retrieval augmented generation (RAG) comes in, allowing you to retrieve data from your own systems to augment what the LLM can reason over.

What is RAG?

Retrieval augmented generation, or RAG, is the term for augmenting the data that goes into the LLM by retrieving data from other systems, and use that data to help the LLM generate answers to your questions.

RAG example

For example, if you have an app that will prompt an LLM to give you the average sentiment of a particular product, you can use RAG to augment the LLM with the customer reviews of that product by extracting the relevant data from your reviews database, then sending that data to the LLM to reason over.

How does your app implement RAG?

If you have a prompt-based app that allows the user to interact using pure text, then your app will start from a prompt that is user generated, such as "What is the average sentiment of the cuddly llama toy". Your app will then use some kind of LLM-powered app framework that has plugins - these are add-ons in the app that can retrieve data. This framework will use the LLM to determine which plugins it needs to call to get data, then send that data back to the LLM to reason over with an updated prompt.

How do you add RAG to your LLM app?

One of the best ways to build an LLM app is to use some kind of AI app framework, such as Semantic Kernel, or LangChain. These frameworks support multiple programming languages, and work with your LLM of choice, for example you can build an app in Python using LangChain that uses Llama 2, or an app in C# using Semantic Kernel that uses ChatGPT. These frameworks have a range of features built in that you would want for an LLM app, such as memory so that the results of one prompt can be used in the next.

These frameworks also support plugins - add-ons that you can build to extend the capability of the LLM, supporting tasks such as RAG. These plugins advertise their capabilities to the framework, and the LLM can use this information to decide which plugins to use depending on the prompt.

How do you build a plugin?

Plugins are built in the same language that you use to build your LLM app with the framework. For example, if you are building a C# app using Semantic Kernel, then you would build your plugin in C#. As part of defining your plugin, you provide a natural language description of what your plugin can do, and the framework will use this to decide which plugins to use.

Here's an example of the outline of a simple C# plugin for Semantic Kernel that retrieves cat facts:

public class CatFactPlugin
{
[KernelFunction]
[Description("Gets a cat fact.")]
public async Task<string> GetCatFact()
{
// Do something here to get a cat fact
}
}

Where does the data come from?

RAG is retrieval augmented generation, so the data that you use to augment the LLM has to be retrieved from somewhere. This could be a third party system, or ir could be one of your own internal systems. And typically you would access these systems via an API. So although we are in the shiny new world of AI, we are still back to the age old problem - we have to integrate with an API. And this means reading the API docs, worrying about authentication and retry strategies, building some JSON to make the request, and then parsing the JSON response, and all the issues that come with that.

How do SDKs help with RAG?

Let's be honest here - very few developers will interact directly with an API. We all write some kind of layer of abstraction over the API to make it easier to use. We write it, and we have to maintain it, which is a lot of work.

This is where generated SDKs come in. SDKs are software development kits that wrap the API, and provide a simpler way to interact with the API, the ultimate layer of abstraction. By using an SDK, you have strong typing (depending on your programming language of choice of course), best practices like authentication built in, and you don't have to worry about the JSON parsing. You also get autocomplete in your IDE, the ability for AI coding tools like GitHub copilot to help you, and inline documentation.

And the best thing about generated SDKs is that they are automatically generated from your OpenAPI spec. This means that you don't have to write the SDK, or maintain it - you just generate it, then use it. And once generated, it can be kept up to date automatically inside your CI/CD pipelines.

Generating SDKs for your RAG plugins

When it comes to generating SDKs, liblab is your friend. liblab is a platform that generates SDKs from your OpenAPI spec, so you can use them in your app. Whether you are accessing internal APIs, or third party APIs, all you need is an API spec, and liblab will generate the SDK for you.

We've recently released a full tutorial that will walk you through how to add retrieval augmented generation (RAG) to your AI app using autogenerated SDKs that wrap your internal APIs. This tutorial uses Semantic Kernel and ChatGPT, along with the C# SDK generation capabilities of liblab, and takes you through the process of building a plugin that retrieves cat facts, and using that plugin in your app. Whilst cat facts are important, I understand you probably want to use your own internal systems, but the same principals apply to any API!

A cute plushie cat sitting on a laptop keyboard

Check it out on the liblab developer portal.

Learn how to add RAG to your apps using Semantic Kernel and C# SDKs.

For example, to implement the cat fact plugin mentioned earlier, you could use the Cat Facts API. Using liblab, you can generate a C# SDK for the Cat Facts API.

You can find a liblab config file to generate the cat facts SDK in a template repo we've published to augment the tutorial.

Once you have the cat facts SDK, you can use it in your plugin to retrieve cat facts:

using CatFacts;

public class CatFactPlugin
{
private readonly CatFactsClient _client = new();

[KernelFunction]
[Description("Gets a cat fact.")]
public async Task<string> GetCatFact()
{
Console.WriteLine("CatFactPlugin > Getting a cat fact from the Cat Facts API...");
var response = await _client.Facts.GetRandomFactAsync();
Console.WriteLine("CatFactPlugin > Cat fact: " + response.Fact);
return response.Fact;
}
}

In this code we just have 2 lines of code to get the cat facts from the SDK - the declaration of a field to hold the SDK client, and the call to the SDK to get the cat fact. The SDK takes care of all the complexity of calling the API, and parsing the response. Much nicer than writing all that code yourself!

This plugin can then be used in your app to retrieve cat facts, and augment the LLM with the data. For example, having the LLM give you the cat fact in the style of a pirate:

Terminal
User > Give me a fact about cats in the style of a pirate
CatFactPlugin > Getting a cat fact from the Cat Facts API...
CatFactPlugin > Cat fact: A group of cats is called a clowder.
Assistant > Arr matey! Be ye knowin' that a gatherin' of meowin' seafarers,
them cats, be called a clowder? Aye, a fine group of whiskered buccaneers they be!

A cute plushie cat dressed as a pirate

Again, maybe less helpful in the real world, but you get the idea! In the real world you could use the LLM to reason over your own data, for example retrieving data from an internal review system, and providing a list of the most popular products based off the reviews.

Conclusion

Adding retrieval augmented generation (RAG) to your AI app can be a powerful way to help your LLM reason over your own data. Using autogenerated SDKs to wrap your internal APIs makes it easier to add RAG to your app, giving you more time to focus on building the best AI experience for your users.

Get started with liblab today!

← Back to the liblab blog

This year, we will be sponsoring apidays New York in New York City from the 30th April to 1st May. We look forward to meeting you in person and discussing our latest SDK generator.

Start generating your SDK for free today - liblab.com/join

Why stop by?

So why should you attend and stop by the liblab booth? Here are a few reasons:

Meet the liblabers

First of all, our booth will be packed with our top Engineers (friendly, too). Come for a chat about your API and SDK needs, and we'll show you how liblab can help. We can also help with guidance on yor API strategy to help you be ready to generate SDKs.

See the 1-minute demo

Hear about our product updates and new features to help with documentation and API specs. We know manually generating SDKs is a pain. We will demo how painful it can be and how we can reduce your pain. Worth your visit.

Visual Studio Code showing some code using a llama store SDK in Python

Snap a photo with liblab's Llama

Let's be honest: the best part of our booth is a 7-foot Llama. Snap a pic with our llama, tweet it with the hashtag #liblabLlama and tag @liblaber to get a special sticker!

A llama mascot riding a mechanical bull

More from liblab:

Hear us on stage, and if it's anything like the last event we attended, you'll even get to do some stretching exercises with us. We're not kidding.

Jim on a stage presenting with his arms outstretched, and the audience also stretching their arms

I'll be giving a talk at 4:30pm on the 30th April, called Build a terrible API for people you hate in the DX/API track:

We've all been there - you've been asked to build an API to be used by someone you really dislike. Maybe it's the person who keep stealing your milk from the company kitchen, or the one who asks long winding questions just as the 5pm Friday meeting is about to end. It's someone who annoys you, and you have to build them an API.

So malicious compliance time! You have to build them an API, but no-one said it has to be good. Here's your chance to get revenge on this person by building the Worst. API. Ever. This session will show you how, covering some of the nastiest ways to create an API that is terrible to use. From lack of discoverability, to inconsistent naming, this session will have it all!

And maybe if you have to create an API for someone you love, this might give you some pointers as to what not to do...

Get your ticket

Sign up now at apidays.global/new-york!

← Back to the liblab blog

We're thrilled to announce the preview launch of our revamped Python SDKs, bringing new capabilities and improvements to simplify your development experience. We've focused on enhancing usability, efficiency, and overall developer satisfaction. From seamless input handling, to automated validation and intuitive request building, our v2 SDKs are designed to empower developers like never before.

In this article, we'll take a closer look at the key features and enhancements introduced in our v2 Python SDKs, showcasing how they can accelerate your development process and streamline interaction with APIs. All the code snippets you'll encounter have been automatically generated using liblab, using v2 of our Python SDKs, and utilizing samples of OpenAPI Specs.

Casting the input

Simple is better than complex. Complex is better than complicated.

With the release of the new version of the Python SDKs, we are introducing a new feature called cast_models. This tool is designed to simplify the process of handling user input by automatically converting values into model instances. By doing so, users can concentrate more on the core logic of the SDK and not get overwhelmed by the complexities of input handling.

To understand how it works, consider the following example:

@cast_models
def create(self, request_body: CreateRequest) -> ApiResponse:
...

Here, the cast_models decorator is applied to the create method. This means that developers can simply invoke create with a dictionary representing the request_body, and it will seamlessly transform into an instance of CreateRequest.

The cast_models feature not only facilitates the conversion of dictionaries to models but also adeptly handles the conversion of primitives into their expected types. For instance, "2" is automatically cast to 2, Enum values are transformed into Enum instances, and types within lists are cast effortlessly, among other capabilities.

Validating the input

Errors should never pass silently.

Once the input is cast into their expected types through cast_models, the next step is ensuring the integrity and validity of the data. In our v2 Python SDKs, we are employing a new validation mechanism to accomplish this task.

Let's take a closer look at how validation is integrated into our workflow with a practical example:

...
"parameters": [
{
"name": "LlamaId",
"in": "path",
"required": true,
"schema": {
"type": "string",
"description": "The ID of a llama",
"title": "LlamaId",
"pattern": "^uuid:\\d+$"
},
},
{
"name": "limit",
"required": true,
"in": "query",
"example": 10,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 100
}
},
],
...

In this OpenAPI spec, the LlamaId parameter is defined as a uuid, and the limit parameter is subject to a minimum and maximum. These constraints are automatically translated into validation rules in our Python SDKs.

@cast_models
def get_something(
self,
llama_id: str,
limit: int,
sort_by: SortBy = None,
tags: List[float] = None,
) -> PaginatedSomethingResponse:

...
Validator(str).pattern("^uuid:\d+$").validate(llama_id)
Validator(int).min(1).max(100).validate(limit)
Validator(SortBy).is_optional().validate(sort_by)
Validator(float).is_array().is_optional().validate(tags)

In the code snippet above, the validation rules are automatically generated based on the API specification. For instance, the llama_id parameter is validated against a pattern match to ensure it conforms to the format "uuid:[number]". Similarly, the limit parameter is subject to minimum and maximum constraints, with their values dictated by the API spec.

Each parameter is submitted to validation to ensure compliance with the criteria defined in the API specification, maintaining data integrity and preventing unnecessary API consumption.

Building the request

There should be one - and preferably only one - obvious way to do it.

Once the input parameters are cast and validated, the next step is to build the request. We achieve this using a simplified and intuitive approach within our Python SDKs.

Let's dive into how we build the requests using a practical example:

@cast_models
def get_something(
self,
llama_id: str,
limit: int,
sort_by: SortBy = None,
tags: List[float] = None,
) -> PaginatedSomethingResponse:
...
Validator(float).is_array().is_optional().validate(tags)

serialized_request = (
Serializer(f"{self.base_url}/something/{{llama_id}}", self.get_default_headers())
.add_path("llama_id", llama_id)
.add_query("limit", limit)
.add_query("sort_by", sort_by)
.add_query("tags", tags)
.serialize()
.set_method("GET")
)

Here we utilize the Serializer class to build the request URL with path parameters and query parameters effortlessly. Each parameter is serialized and incorporated into the request.

The Serializer class supports all serialization types described by OpenAPI specifications. This flexibility allows developers to seamlessly serialize URL components present in headers, cookies, path parameters, and query parameters in compliance with the OpenAPI standards. Whether it's form serialization, space-delimited serialization, pipe-delimited serialization, or deep object serialization, our Serializer class empowers developers to comply with the API specifications effortlessly.

The following example demonstrates how this functionality also support non-default serialization styles:

Serializer ...
.add_path("llama_id", llama_id, explode=True, style="matrix")
.add_path("status", status, explode=False, style="label")

By using a consistent and straightforward method for constructing requests, our Python SDKs v2 promotes simplicity and clarity, making it easier for developers to interact with the API and focus on their core objectives.

Validating the output

Special cases aren't special enough to break the rules.

After retrieving the response, we invoke the unmap function to parse the response into a model instance:

@cast_models
def get_something(
...

response = self.send_request(serialized_request)

return PaginatedSomethingResponse._unmap(response)

The unmap function attempts to deserialize the response into the corresponding model. However, if this process fails due to unexpected data format or missing fields, it raises an error.

By enforcing output validation, our Python SDK maintains consistency in data representation, making possible for our users to identify any misconceptions their might have about their data representations.

Mapping to Python

Readability counts.

The properties in your API do not always match the naming conventions in Python, and beyond that, they might be reserved words. To solve that problem our v2 Python SDKs have a mapping functionality.

To illustrate, let's check the following model definition:

@JsonMap(
{
"is_enabled": "isEnabled",
"something_list": "somethingList",
"user_role": "userRole"
}
)
class PaginatedSomethingResponse(BaseModel):
...

def __init__(
self,
page: int,
is_enabled: bool,
something_list: SomethingList,
user_role: Role,
org: OrgResponse = None,
):
self.page = page
self.is_enabled = is_enabled
self.something_list = self._define_list(something_list, SomethingList)
self.user_role = self._enum_matching(user_role, Role.list(), "role")
if org is not None:
self.org = self._define_object(org, OrgResponse)

Here, the @JsonMap annotation is employed to map keys from the Python representation to the corresponding values expected by the API. This ensures that the properties of the models align with Python’s naming conventions and the structure of the API data.

Descriptions and snippets

In the face of ambiguity, refuse the temptation to guess.

In addition to the powerful features introduced in our v2 Python SDKs, we've incorporated comprehensive descriptions and snippets, enhancing clarity and usability for developers.

The snippets can help developers to integrate SDK functionality into their projects with minimal effort. These snippets cover a wide range of SDK functionality and can be easily accessed from the README files generated with the SDK.

The following Snippet was generated for our Llama Store SDK:

from llama_store import LlamaStore, Environment
from llama_store.models import LlamaCreate

sdk = LlamaStore(
base_url=Environment.DEFAULT.value
)

request_body = LlamaCreate(**{
"name": "name",
"age": 2,
"color": "brown",
"rating": 3
})

result = sdk.llama.create_llama(request_body=request_body)

print(result)

We've also integrated reStructuredText (reST) docstrings into our SDKs. These docstrings serve as a rich source of documentation, providing detailed information about the SDK.

@cast_models
def get_something(
self,
llama_id: str,
limit: int,
sort_by: SortBy = None,
tags: List[float] = None,
) -> PaginatedSomethingResponse:
"""
Retrieve something based on specified parameters.

:param llama_id: The identifier of the something to retrieve.
:type llama_id: str
:param limit: The maximum number of results to return.
:type limit: int
:param sort_by: The sorting criteria for the results (optional).
:type sort_by: SortBy, optional
:param tags: The list of tags to filter the results (optional).
:type tags: List[float], optional
:return: Paginated response containing something data.
:rtype: PaginatedSomethingResponse
"""
...

The new format of docstrings is compatible with documentation generation tools like Sphinx.

Overall objectives/conclusion

Beautiful is better than ugly.

In conclusion, the v2 release of our Python SDKs embodies our core principles of generating human-friendly code and removing complexity from the user's hands. By prioritizing clarity and ease of use, developers can focus on their objectives without being bogged down by complex API interactions.

While maintaining support for essential features like authentication, retry, and refresh token handling out of the box, the v2 SDKs elevate the user experience with streamlined input handling, automated validation, and intuitive request building.

We invite you to experience the benefits of our new v2 SDKs by specifying "liblabVersion": "2" in the "python" customization section of your liblab config file:

{
"languages": [
"python"
],
"languageOptions": {
"python": {
"liblabVersion": "2"
}
}
}

Dive into simplified API interaction and unleash your productivity with our user-centric design approach.

Join our Discord community to share your questions, feedback, and experiences with the new SDKs. We look forward to hearing from you!

← Back to the liblab blog

At liblab, our exploration into leveraging AI, specifically Large Language Models (LLMs), to see if it can be used to contribute to the generation of Software Development Kits (SDKs) has been both enlightening and challenging. This exploration aimed to enhance our internal development processes and maintain a competitive edge in the rapidly evolving tech landscape. Despite the hurdles, our experiences have provided valuable insights into the potential and limitations of current AI technologies in software development.

The experiment

Our exploration began with the goal of generating SDKs from OpenAPI specifications. This process involves several stages:

  • Generating OpenAPI specs from documentation
  • Creating SDK components such as models and services
  • Integrating custom hooks based on prompts.

Our experiments helped us better evaluate the potential in the space.

Achievements

We managed to partially generate SDK components, demonstrating the potential of AI in streamlining certain aspects of development. This achievement is a testament to the capabilities of AI to assist in automating repetitive and straightforward tasks within the SDK generation process.

This may sound great, but the downsides far outweigh the benefits.

Limitations

Despite the achievements, the integration of these components into a cohesive SDK proved to be overly time-consuming and highlighted significant limitations:

1. Non-determinism and hallucinations

In the context of LLMs, “hallucination” refers to a phenomenon where the model generates text that is incorrect, nonsensical, or not real.

A Gentle Introduction to Hallucinations in Large Language Models

LLMs showed a tendency to produce variable outputs and factual inaccuracies. This inconsistency poses challenges in achieving reliability, especially since SDKs generated in different sessions may not be compatible due to hallucinated content or changes in the SDK's public surface area after adding new endpoints.

In some cases, the LLM would entirely disregard the given specification or make incorrect assumptions about specific endpoints, resulting in non-functional code.

2. Input and output limitations

The models faced difficulties with the volume of code that could be processed and generated in a single instance, hampering their ability to handle complete codebases. LLMs use tokens, with a token approximately equivalent to a couple of characters, and different LLM models have different token limits, for example the largest GPT-4 model can take 128,000 tokens as input, and return only 4,000 tokens as output, which is too small for an SDK.

Over time this will reduce as LLMs have larger token limits, but for now, it's a significant limitation.

3. Response time and cost implications

The increased response time and associated costs of utilizing LLMs for development tasks were non-negligible, impacting efficiency. For instance, a single call to the OpenAI API can take upwards of 15 seconds, with multiple calls needed. liblab can generate multiple SDKs in approximately 10 seconds.

4. State and memory constraints

LLMs demonstrated limitations in maintaining conversational memory and managing state, complicating extended code generation sequences. This is related to the input and output limitations, but also the fact that LLMs are not designed to be used in a conversational manner.

Memory can be implemented by passing all the previous inputs and outputs into the model, but this is not practical for SDK generation as this drastically increases the number of tokens used, the response time, and cost. Other solutions are possible, such as using vector databases, but these add complexity and cost.

5. Security concerns

A significant limitation that cannot be overlooked when considering AI-generated SDKs is the potential for increased security risks. As AI models, including LLMs, are trained on vast datasets of existing code, they inherently lack the ability to discern secure coding practices from insecure ones. This can lead to the generation of code that is vulnerable to common security threats and weaknesses.

For more information on this topic refer to The Snyk 2023 AI Code Security Report.

Insights into AI's application in SDK generation

Our journey has underscored the importance of clarity, precision, and simplification in interactions with LLMs. We learned the value of structuring prompts and managing code outputs effectively to optimize the model's performance. However, our experiments also highlight the current impracticality of relying on AI for SDK generation due to the critical issue of non-determinism and hallucinations.

The verdict on AI-generated SDKs

Given the challenges in achieving the necessary level of accuracy, consistency, and functionality, the current state of AI technology does not offer a viable alternative to traditional SDK generation methods. Our findings suggest a need to approach AI with caution in this context, emphasizing the irreplaceable value of human expertise and tailored solutions.

The role of AI in enhancing developer experience at liblab

We are committed to providing developers with tools that are not only powerful but also user-friendly and easy to integrate. Our exploration has reinforced our belief in leveraging AI where it adds value without compromising on quality or usability, ensuring that we prioritize human-centered design in our tool development.

Future directions

Informed by our experiences, we remain optimistic about the potential of AI to enhance our offerings in ways that do not involve direct SDK generation. We are exploring other avenues where AI can positively impact the developer experience, focusing on areas that complement our strengths and meet our customers' needs.

Conclusion

The journey of leveraging AI at liblab has been a path of discovery, filled with both challenges and opportunities. While AI-generated SDKs cannot not replace traditional methods, the potential of AI to transform development practices remains undeniable.

We look forward to continuing our exploration of AI technologies, constantly seeking ways to innovate and improve the tools we offer to the developer community.

← Back to the liblab blog

We're thrilled to announce a significant update to our SDK documentation generation: Markdown support is here! This new feature is designed to make your documentation more readable, more engaging, and easier to write. Whether you're a seasoned API developer or just starting out, Markdown can simplify the way you create and maintain your documentation. Let's dive into what this means for you and how you can leverage these new capabilities.

What is Markdown?

Markdown has become the lingua franca of the web for writing content. Its simplicity and readability make it an excellent choice for writing documentation. Unlike HTML or other markup languages that are often cumbersome to write and read, Markdown allows you to format text using plain text. This means you can create headers, lists, links, and more, without taking your hands off the keyboard to interact with with tags or styling buttons.

For those unfamiliar with Markdown, it's a lightweight markup language created by John Gruber and Aaron Swartz. Markdown enables you to write using an easy-to-read, easy-to-write plain text format, which then converts to structurally valid HTML (or other formats) for viewing in a web browser or other platforms. This makes it an ideal choice for writing online documentation, as it's both human-readable and machine-convertible, ensuring your documentation is accessible both in raw and rendered forms.

Supported Features

Our SDK documentation generator now supports the following Markdown features:

  • Headers: Structure your documentation with headers to define sections clearly and improve navigation. Use different levels of headers (e.g., #, ##, ###) to create a hierarchy and organize content logically.
  • Bold and Italics: Add emphasis to your text with bold and italics, making important information stand out.
  • Images: Integrate images into your documentation to provide visual examples, diagrams, or illustrations. This can greatly aid in explaining complex concepts, workflows, or architecture, making your documentation more comprehensive and accessible.
  • Tables: Organize information neatly in tables. This is perfect for parameter lists, version compatibility, and more.
  • Lists: Organize information in lists to improve readability and structure. Lists are great for step-by-step instructions, feature lists, or any information that benefits from a clear hierarchy or grouping.
  • Inline Code and Code Blocks: Highlight code snippets directly in your documentation. Inline code for small references and code blocks for larger examples.
  • Links: Create hyperlinks to external resources, further reading, or cross-references within your documentation.
  • Blockquotes: Use blockquotes to highlight important notes, warnings, or quotes from external sources.

With these features, you can create more structured, readable, and engaging SDK documentation, allowing users to better understand and utilize your SDK.

How to Use the New Features

Incorporating Markdown into your SDK documentation is straightforward. Here's how to get started:

  1. Open your OpenAPI specification file.
  2. Find the description fields where you want to add formatted documentation.
  3. Insert your Markdown directly into these fields.

This Markdown will be automatically converted into beautifully formatted documentation when generated through with liblab.

Example

Here's an example of how you can use Markdown in your OpenAPI specification. In this case, we are using the classic Pet Store API Spec with some Markdown added to the description:

openapi: 3.0.0
servers:
- url: https://petstore.swagger.io/v2
description: Default server
- url: https://petstore.swagger.io/sandbox
description: Sandbox server
info:
description: |
This is a sample server Petstore server.
You can find out more about Swagger at
[http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).
For this sample, you can use the api key `special-key` to test the authorization filters.


# Introduction
This API is documented in **OpenAPI format** and is based on
[Petstore sample](http://petstore.swagger.io/) provided by [swagger.io](http://swagger.io) team.

# Cross-Origin Resource Sharing
This API features Cross-Origin Resource Sharing (CORS) implemented in compliance with
[W3C spec](https://www.w3.org/TR/cors/).
And that allows cross-domain communication from the browser.
All responses have a wildcard same-origin which makes them completely public and accessible to
everyone, including any code on any site.

# Authentication

Petstore offers two forms of authentication:
- API Key
- OAuth2
OAuth2 - an open protocol to allow secure authorization in a simple
and standard method from web, mobile and desktop applications.

version: 1.0.2
title: Swagger Petstore

This Markdown will be automatically converted into beautifully formatted documentation when generated through liblab:

The pet store docs with rich text in the description. This has headers, links, bullet points and bold text

Future Enhancements

We're not stopping here! Our team is dedicated to improving and expanding the capabilities of our SDK documentation.

Stay tuned for updates, and don't hesitate to share your feedback and suggestions. Your input is invaluable in making our tools even better. Please feel free to contact us to request features or improvements!

We hope you're as excited about this update as we are. Markdown support is a big step forward in making your SDK documentation more accessible and easier to understand.

← Back to the liblab blog

This year, we will be sponsoring the Nordic APIs Summit in Austin, TX on March 11-13. We look forward to meeting you in person and discussing our latest SDK generator.

Start generating your SDK for free today - liblab.com/join

Why stop by?

So why should you attend and stop by the liblab booth? Here are a few reasons:

Meet the liblabers

First of all, our booth will be packed with our top Engineers (friendly, too) demoing how to save developers time and effort by generating SDKs for your APIs in your own language. Coding and conversation language 🙂

A group of people posing for a selfie wearing liblab shirts standing in a carpark. 2 of the team are wearing sunglasses, and another is making a peace sign

See the 1-minute demo

Hear about our product updates and new features to help with documentation and API specs. We know it's a pain. We will demo how painful it can be and how we can reduce your pain. Worth your visit.

Visual Studio Code showing some code using a llama store SDK in Python

Snap a photo with liblab's Llama

Let's be honest: the best part of our booth is a 7-foot Llama. Snap a pic with our llama, tweet it with the hashtag #liblabLlama and tag @liblaber to get a special sticker!

A group of people wearing liblab love your SDK shirts posing with a large llama mascot also wearing the same shirt. Behind the group is the liblab booth from API world

More from liblab:

Hear us on stage, and if it's anything like the last event we attended, you'll even get to do some stretching exercises with us. We're not kidding.

Jim on a stage presenting with his arms outstretched, and the audience also stretching their arms

We will be hosting 3 sessions:

  • Build a terrible API for people you hate - 12th March, 1:10PM, API design technical track

    We've all been there - you've been asked to build an API to be used by someone you really dislike. Maybe it's the person who keep stealing your milk from the company kitchen, or the one who asks long winding questions just as the 5pm Friday meeting is about to end. It's someone who annoys you, and you have to build them an API.

    So malicious compliance time! You have to build them an API, but no-one said it has to be good. Here's your chance to get revenge on this person by building the Worst. API. Ever. This session will show you how, covering some of the nastiest ways to create an API that is terrible to use. From lack of discoverability, to inconsistent naming, this session will have it all!

    And maybe if you have to create an API for someone you love, this might give you some pointers as to what not to do...

  • From APIs to SDKs: Elevating Your Developer Experience With Automated SDK Generation - 12th March, 2:50PM, Developer experience technical track

    APIs are everywhere and are a great way for developers to access your service. But not all developers want to access APIs directly. Most want to use SDKs in their preferred programming language using the tools they already know and use everyday. These not only feel more intuitive to a developer, but bring features like type safety, documentation, and code completion.

    In this demo-heavy session, Jim will compare APIs and SDKs and show just how much a well crafted SDK can improve the developer experience. Releasing changes to your customer quickly is something every development team strives for, so Jim will go on to show you how this process can be automated, including in your CI/CD pipelines so that every API change can be released as an SDK as soon as possible with minimal engineering effort.

    By the end of this session you will have a new appreciation for SDKs and understand that creating and maintaining these does not have to be burdensome. You'll be ready to automate this process yourself and improve your own APIs developer experience.

  • 3 Quick Steps to Generate SDKs for Your APIs - 13th March, 10:10AM, Demos and lightning talks

    Learn how to generate SDKs for your APIs in 3 quick steps using liblab.

Get your ticket

Sign up now at nordicapis.com/events/austin-api-summit-2024!

← Back to the liblab blog

SDKs are everywhere, and help developers build software faster and easier. In this post I take a look at some examples of a few SDKs, and talk through the use cases and characteristics of a good SDK.

What is a Software Development Kit (SDK)?

We cover this a lot in one of our other blog posts - how to build an SDK from scratch, but essentially Software Development Kits, or SDKs, are code libraries containing an abstraction layer that makes it easier to interact with a piece of software or hardware using your preferred programming language, speeding up your application development process.

A block diagram of code calling an SDK that calls an API. The code is represented by a plushie llama using a laptop, the arrows between blocks are plushie brown arrows with a neutral facial expression. The SDK is a plushie block fox with SDK written on it, and the API is a plushie block with API written on it, a smiley face, and a swirl of cream on top.

The developers code interacts with the SDK, and that in turn interacts with an API, hardware, or other software.

Some examples of types of SDKs include:

  • API SDKs - these are used to interact with an API, such as the Twitter API, or the Stripe API.
  • Hardware SDKs - these are used to interact with hardware, ranging from consumer devices like printers, to IoT devices, smart consumer devices, and more.
  • Mobile SDKs - these are used to interact with mobile devices, such as the iOS or Android SDKs. If you want to use your phones camera, or handle notifications, you need to use the mobile SDKs.
  • UI SDKs - these are used to implement user interface components, in web sites, on mobile apps, or in desktop applications.

List of SDK Examples

There are many types of SDKs, and thousands of SDKs available. Here are a few examples of the types of SDKs mentioned above:

API SDK

An API SDK is a an SDK that makes it easier to use Application Programming Interfaces, or APIs. Many SaaS and cloud companies have APIs to use their tools and products, and calling these APIs directly is not usually the best approach. You can easily end up writing a lot of boilerplate code to handle things like authentication, retries, and more, in your programming language of choice.

A cute llama using a laptop

An API SDK on the other hand will provide you with an SDK in the languages you are using, and it will handle all of the boilerplate code for you, usually implementing the best practices for that API. For example, an SDK can implement authentication in a way that makes sense for the API, or handle retries and backoff in the most appropriate way.

These SDKs are also structured to make sense to the developer using them. This might be by splitting up the API into multiple SDKs, or wrapping multiple APIs in one SDK. They will also provide code examples, documentation, and more in the available SDK languages.

You can read more on the differences between an SDK and an API in our blog post SDK vs API: what's the difference?

Examples of API SDKs include:

  • Stripe SDK - this SDK makes it easier to interact with the Stripe API to handle payments. The Stripe SDKs wrap their APIs for a huge range of programming languages and technologies.
  • Twilio SDK - this SDK makes it easier to interact with the Twilio API to handle communications, such as SMS, voice, and video.
  • AWS SDK - this SDK makes it easier to interact with the AWS API to handle cloud services, such as storage, databases, and more.

Hardware SDK

Hardware SDKs provide an abstraction layer for communicating with hardware tools rather than software tools. This could be a device connected to a computer, such as a bar code scanner, to remote devices such as Internet of Things (IoT) devices, to hardware connected to a mobile device, such as credit card readers.

A cute llama using a credit card

Communication with hardware is typically low level code, and can be very complex. A hardware SDK will provide a higher level of abstraction, making it easier to interact with the hardware.

Examples of hardware SDKs include:

  • Square reader SDK - the Square Reader is a credit card and contactless payment device that connects to mobile phones. This SDK allows you to integrate payments into your mobile apps using the reader hardware. This reader can be connected over an audio jack, so the SDK handles converting audio signals to the data the reader needs, and back to the data your application needs.
  • Tuya IoT App SDK - this SDK allows mobile app developers to build apps that interact with Tuya's range of smart home and IoT devices. It can handle pairing of devices, device configuration, and device control, over multiple protocols from Zigbee to Matter. The SDK abstracts the protocols and device types, making it easier to build apps without caring about the underlying technology.
  • Zebra Scanner SDK - this SDK allows you to build applications that interact with Zebra's range of barcode scanners. It provides a higher level of abstraction than the low level barcode scanner APIs, making it easier to build applications that interact with the scanners.

Mobile SDK

Mobile SDKs are used to interact with mobile devices, such as iOS and Android. These SDKs provide a higher level of abstraction than the low level APIs provided by the mobile operating systems, making it easier to build applications that interact with the devices.

A cute llama using a mobile phone

Some mobile SDKs are provided by the device manufacturer, and usually these are limited in the SDK languages you can use. The are third party SDKs that sit on top of these, and provide support for other languages, or a consistent development experience across multiple devices.

Examples of mobile SDKs include:

  • iOS SDK - this SDK provides a range of APIs for building applications on iOS devices. It includes APIs for interacting with the device hardware, such as the camera, and for interacting with the operating system, such as handling notifications. This SDK primarily supports Swift, but you can create apps using C++ and Objective C.
  • Android SDK - similar to the iOS SDK, this SDK provides a range of APIs for building mobile applications on Android devices. This SDK primarily supports Java and Kotlin, but you can create Android apps in C++.
  • Flutter SDK - this SDK provides a range of APIs for building mobile applications on both iOS and Android devices. It provides a consistent development experience across both platforms, and supports the Dart programming language.
  • .NET MAUI - this SDK provides a range of APIs for building mobile applications on both iOS and Android devices. It provides a consistent development experience across both platforms, and supports C# and F#.

UI SDK

UI SDKs provide user interface components for you to use in your web, mobile or desktop app. These abstract out a range of user experiences in different programming languages, and provide a consistent look and feel across different platforms.

A cute llama designing a web site

Examples of UI SDKs include:

  • DevExpress - this SDK provides a range of user interface components for web, mobile and desktop applications.
  • MUI - this SDK provides a range of user interface components for web applications, and is built on top of React.
  • Material Design - this SDK provides a range of user interface components for web applications, as well as mobile apps built using Android or Flutter. This is built on top of Google's Material Design system.

Use Cases for SDK Implementation

With all the different types of SDKs, the general theme is the same - they provide a way to build functionality into your application without having to write all the code yourself. Here are some use cases for implementing an SDK:

Payments

We all like being paid right? But handling payments can be complex, with a lot of edge cases to handle. A payments SDK such as Stripe can handle all of this for you, from handling the user interface for entering payment details, to handling the communication with the payment provider, and handling the response from that payment provider. If you are building a platform where you need to charge someone, you can add payments in only a few lines of code calling the relevant SDK.

Analytics and metrics

As developers we want to know who is using our apps, what features they are using, how they discover those features, and in-depth details when things go wrong. It's reasonably quick these days to add analytics and metrics to an application using an SDK such as Sentry. Again, a few lines of code and you have analytics, metrics, and error tracking.

Social Media

Social media has changed how we interact with our customers, potential customers, friends and colleagues. There is a lot a developer can do with social media, from getting alerts when their company is mentioned, to scheduling posts. A social media SDK can allow you to integrate this functionality into your own apps.

Custom relationship management (CRM)

Custom relationship management, or CRM, software often needs to integrate with other systems, such as the systems you are building as a developer. For example, if you wanted to add a contact form to your website, and want to feed that customer data to your CRM. This can be done using the CRM SDK, with different SDK capabilities from a full UI component that does everything, to a more lighter weight SDK where you send the form data to an SDK call.

Characteristics of a Good SDK

Whilst in principal an SDK should make your development experience better, this is not always the case. There are some great SDKs out there, as well as some utterly terrible ones.

Here are some characteristics of a good SDK:

  1. Easy to install - whilst easy is a subjective term, your SDK needs to be easy for your users to install. Sometimes this is as simple as ensuring it is hosted on a package manager, such as npm, pip, nuget, or maven.

  2. Documentation - without good documentation an SDK can vary from being hard to use to being useless. Good documentation should include reference documentation in all supported languages, guides to implementing common functionality, and tutorials to get you started quickly.

  3. Code samples - developers love to copy and paste, and having great code samples really helps developers build apps quickly by taking anything from inspiration, to huge swathes of code, from your examples. These can be inside your documentation, or in a separate examples repository on GitHub. Good code samples can even help guide AI coding assistants inside your integrated development environment or IDE.

  4. Sample apps - an extension to code samples, sample apps can help your users understand the bigger use cases for your SDK, and see how it can be implemented across a larger application, instead of just in one place. As software developers create their apps, these samples can speed up their time to deliver as they can provide a complete reference implementation. For example, an app with example code showing how user authentication can be implemented in one location in your app, and then how that authenticated user can be used across the app.

  5. Idiomatic to the language - a good SDK supports a range of programming languages, and for each language the implementation should be idiomatic to that language. From documentation in the right format to allow for easy integration with IDEs, to using the right language features, a good SDK should feel like it was written by a developer who knows the language well making software development using it feel natural. It should also not re-invent the wheel, using the standard libraries and frameworks for that language where possible.

  6. Few dependencies - it's very easy for an SDK to have a huge amount of dependencies, and this can lead to problems managing these when you want to add dependencies to your own project. A good SDK should have as few dependencies as possible.

  7. Simple to use - simple is another subjective term, but a good SDK should feel to the developer like it is easy to use, and expresses concepts and patterns in a user centric way focusing on the use cases that a developer might have. Your SDK should be written with an understanding of the types of problems your users want to solve, and provide convenient ways to do this, not just be a wrapper around your internal database structure or your hardware. For example with a bar code scanner SDK, developers using it probably just want to get an event fired when a barcode is scanned with the bar code number, not have to worry about writing control loops to monitor for what the scanner is detecting all the time, polling to see if a bar code is found, then getting the code.

  8. Up to date - a good SDK should be up to date with the latest version of the API or hardware it is wrapping. This can be a challenge, but it is important to keep your SDK up to date, as your users will want to use the latest features of your API or hardware. To help with this, make your SDK as maintainable as possible (for some tips with TypeScript SDKs check out our Quick tips for making your SDK more maintainable in TypeScript: routes edition article). For API SDKs consider auto-generating them using liblab to avoid having to spend time maintaining them when your API is updated, adding auto-generation to your development process.

Conclusion

A good SDK can greatly improve the developer experience for your users. For hardware they get a nice abstraction that is easier to program against rather than sending raw, low level hardware commands, for an API they get models and service classes that make it easier to interact with that API, handling things like authentication, retries and more for you. For more on should you build an SDK, check out our article on 'why do I need to build an SDK'.

SDKs are a great thing to provide to your customers, but can be a lot of work to build. This is where liblab comes in, allowing you to quickly generate SDKs for your APIs.

If you have an API and want to improve your users developer experience with an SDK, sign up for liblab now at liblab.com/join.

← Back to the liblab blog

As an experienced engineer, I've learned the value of simplicity and ease of getting things done. Life is too short to spend on writing boilerplate code, or dealing with the complexities of lowest common denominator tooling. I want to focus on the business problem I'm trying to solve, not the plumbing.

This is why I'm always a fan of a well-crafted SDK, a tool that makes it easy to use a service or API. In this post we look at the process of creating SDKs, from concept to creation, and show how you can automate the process using liblab.

What is an SDK?

Let's start with the basic question - what is an SDK? An SDK, short for Software Development Kit, is a set of tools written in one or more programming languages that make it easier to use a service or API. For this post, I will focus on SDKs for APIs, providing a wrapper around the direct REST calls that a user might make against an API.

An SDK is a great abstraction layer. It is written in the language the developer uses, and provides language idiomatic ways to call the API, managing all the hard stuff for you such as the HTTP calls, the mapping of JSON to objects, authentication, retries, and so on.

A good SDK drastically reduces the code you have to write.

The importance of an SDK

SDKs are important to improve the developer experience of using your service or API. They allow your users to focus on the business problem they are trying to solve, rather than the plumbing of calling your API. This is just as important for public facing APIs from SaaS companies, as it is for internal APIs used by your own developers from your corporate microservices.

Some benefits include:

  1. Intellisense and code completion - you can see the methods and properties available to you, and the parameters they take in your IDE.
  2. Authentication - the SDK can handle the authentication process for you, so you don't have to worry about it.
  3. Built in best practices - you can embed best practices inside the SDK, such as retry logic, so that if a call fails due to rate limiting, the SDK will automatically retry the call after a short delay.

To learn more about the comparison between SDKs and calling APIs directly, check out our post SDK vs API, key distinctions.

How to Build an SDK

Creating SDKs is a multi-step process, and is very time consuming. Not only do you need to design and build the SDK, but you also will want to create SDKs in multiple languages to support your users needs.

This might be less important if you are building SDKs for internal APIs and you only use a single language - for example if you are a Java shop you may only need a Java SDK. However, if you are building a public facing API, you will want to support as many programming languages as possible, so that your users can use the language they are most comfortable with. You will probably want a TypeScript SDK or JavaScript SDK, a Python SDK, a C# SDK, a Java SDK, and so on depending on the programming language priorities of your users.

The steps you would take are:

  1. Design your SDK
  2. Build your SDK
  3. Document your SDK
  4. Test your SDK
  5. Publish your SDK
  6. Maintain your SDK

1. Design your SDK

The first step is to design the SDK. A typical pattern is to mimic the API surface, providing functions that act like your API endpoints. This is a great way to build an SDK - it means your documentation and other user guides can be essentially the same for your API and SDKs, with just different sample code to use the SDK rather than make an API call.

API specification

To do this you will need to know how your API works, which is why it is important that your API has documentation, ideally an API specification such as an OpenAPI spec. Some API designers will start from an OpenAPI spec, others will start with code and autogenerate the OpenAPI spec from that code. Either way, you need to have a good understanding of your API before you can start to design your SDK.

The act of designing your SDK can also be a great way to validate that you have a good, clean API design. If you find that your SDK is hard to design, or that you have to do a lot of work to make it easy to use, then this is a good sign that your API needs improvement. For some tips, check out our post on why your OpenAPI spec sucks.

Paths and components

OpenAPI specs have 2 sections that make designing your SDK easier - paths and components. The paths section defines the endpoints of your API, and the components section defines reusable components, such as schemas for request and response bodies, or security schemes.

You want to use components as much as possible to make it easier to understand the data that is being passed around. Using components also helps you to them as much as possible between endpoints.

For example, if you have an endpoint that returns a single user, it is cleaner to have that user defined as a components/schema/user object. You can then reference that in the endpoint that gets a single user, and wrap it as an array for an endpoint that gets multiple users.

From API spec to an SDK design

Once you have your API spec, you can start to design your SDK. A good design is to provide objects that wrap the requests and responses for your API endpoints, and methods that call the API endpoints.

You will need to consider:

  • What objects will encapsulate the components
  • How paths will be grouped and wrapped as methods
  • The interface to handle authentication
  • Each SDK language will have different idioms, libraries and best practices. You will need to decide how to handle these differences. This might be a challenge if you are not familiar with the language.
  • How to handle best practices such as retries. Do you implement this yourself, or use a library?
  • Naming conventions. It is important to create SDKs that use idiomatic code for the SDK language - for example, if you are building a Python SDK, you want to use Python idioms such as using snake_case for method names, and PascalCase for class names, whereas TypeScript would use camelCase for method names.

2. Build your SDK

After you have designed your SDK, you can start to build the code implementation. This is a manual process, and is very time consuming, especially if you have SDKs in multiple languages.

Components

First you want to create objects to wrap the requests and responses for your API endpoints, defined in the components/schemas section of your OpenAPI spec. These objects are often referred to as models or DTOs (data transformation objects). These are usually 'simple' objects that have properties that map to the properties on the schema, and allow you to write JSON mapping code (or use a built in library) to automatically map the JSON to the object.

Sometimes the objects can be more complex. For example if your API specification defines an anyOf or oneOf - an endpoint that can return one of a range of possible types. Some languages can support this through a union type, others cannot, so you will need to decide how to handle these types. Remember, you need to do this for every SDK language you want to support.

SDK methods

Once you have your models, you can start to build the SDK methods that call your API endpoints. These functions can take models as parameters, and return the models as responses.

You will need to handle making HTTP requests, and the mapping of JSON to objects. You will also need to handle the authentication process, and any other best practices you want to build in such as persisting the HTTP connection, retries and logging.

These methods might also need parameters to match the parameters for the endpoint - both path parameters and query parameters.

For example, if the endpoint is GET /llama/{id} with the Id as a path parameter, you might have a method like this:

class Llama(BaseService):
def get_llama(self, id: int) -> Llama:

where the llama Id becomes a method parameter.

Grouping methods

A good practice is to group these functions into service classes. You might want to do it based off the endpoint - for example having the GET, POST, and PUT methods for a single endpoint in a single class.

API specifications can also define groupings of endpoints, such as OpenAPI tags, so you might want to group your functions based on these tags. You know your API, so pick a technique that works for you.

As you build these methods, you should abstract out as much logic as possible into base service classes, or helper methods. For example, you might want to abstract out the HTTP request logic, the JSON mapping logic, the authentication logic, and the retry logic. This way you can define it once, and share the logic with all your service methods.

SDK client

Finally you will want to put some kind of wrapper object, usually referred to as an SDK client, around the endpoints. This will be the single place to surface authentication, setting different URLs if you have a multi-tenant API, or support different API regions or environments. This is your users entry point to the SDK.

class Llamastore:
def __init__(self, access_token="", environment=Environment.DEFAULT) -> None:
# The llama service
self.llama_service = LlamaService(access_token)

# Set a different URL for different environments
def set_base_url(self, url: str) -> None:

# Set the API access token
def set_access_token(self, token: str) -> None:

3. Document your SDK

An SDK is only as good as its SDK documentation. As you create SDKs, you will also need to write documentation that shows how to install, configure, and use the SDK. You will need to keep the documentation in sync with the SDK, and update it as the SDK evolves. This will then need to be published to a documentation web page, or included in the SDK package.

OpenAPI specs support inline documentation, from descriptions of paths and components, to examples of parameters and responses. This is a great way to document your API, and you can use this to generate proper documentation for your users.

4. Test your SDK

Once your SDK is built, you need to ensure that it works as expected. This means writing unit tests that verify:

  • The JSON expected by and returned by your API can map to the objects you have created
  • The HTTP requests are being made correctly by the SDK methods to the right endpoints
  • Authentication is implemented correctly
  • The best practices such as retries work as expected

You should write unit tests that mock the real endpoint, as well as integration tests that call a real endpoint in a sandbox or other test environment.

5. Publish your SDK

Your finished SDK needs to be in the hands of your users. This means publishing it to a package manager, such as npm for JavaScript, or PyPi for Python.

For every SDK language you will need to create the relevant package manifest, with links to your SDK documentation, and publish it to the package manager. For internal SDKs, you might want to publish it to a private package manager, such as GitHub packages, or a private npm registry.

6. Maintain your SDK

It's not enough to just create SDKs once. As your API evolves, you need to update your both your SDK and SDK documentation to reflect the changes. This is a manual process, and is very time consuming, especially if you have SDKs in multiple languages.

Your users will expect your SDK to be in sync with your API, ideally releasing new features to your SDK as soon as they are released to the API. As well as the engineering effort to update the SDK and SDK documentation, you also need to ensure that during SDK development, your internal processes track API updates, create tickets for the work to update the SDK, and ensure that the SDK is released at the same time as the API.

Every new endpoint would mean a new SDK method, or a new class depending on how you have structured your SDK. Every new schema is a new model class. Every change to an existing endpoint or schema is a change to the existing SDK method or model class. You may also need to update any best practices, such as supporting new authentication schemes, or adding new retry logic.

You will also need to track breaking changes, and update your SDK version as appropriate - a major version bump for breaking changes, a minor version bump for new features, and a patch version bump for bug fixes.

Best practices for building the perfect SDK

When building an SDK, there are a number of best practices you should follow to ensure that your SDK is easy to use, and works well for your users.

  • Provide good documentation and examples - your API spec should be full of well written descriptions, examples, and other documentation that can be ported to your SDK. This will make it easier for your users to get started quickly.
  • Use idiomatic code - your SDK should use the idioms of the language you are building the SDK for. It should match the language's naming conventions, use standard libraries, and follow the language's best practices. For example, using requests in Python, making all your C# methods async, using TypeScript's Promise for asynchronous methods, and so on.
  • Embed security best practices - take advantage of security best practices, from using the latest version of any dependencies with mechanisms to monitor for patches and provide updates, to using the latest security protocols and libraries.
  • Handle authentication - your SDK should handle authentication for your users. This might be as simple as providing a method to set an API key, or as complex as handling OAuth2. You should also provide a way to handle different environments, such as development, staging, and production.

Automating the SDK build with liblab

Creating SDKs is a lot of work that only gets bigger as your API grows, or you want to support more languages. This is where automation is your friend. liblab is a tool that can take your API specification, such as an OpenAPI spec, and autogenerate SDKs for you in multiple languages.

The SDK generation process will generate the models and service classes for you, with all the required mapping code. It will also generate your best practices such as authentication and retries, and you can configure these via a configuration file. You can also write code that is injected into the API lifecycle to add additional functionality, such as logging or custom authentication with the liblab hooks feature.

The flow for using liblab - an api spec and config file goes in, and an SDK and documentation comes out. The flow for using liblab - an api spec and config file goes in, and an SDK and documentation comes out.

SDK generation is fast! A typical developer flow is to spend a few hours generating SDKs the first time as you configure the generation process to meet your needs. This is an iterative cycle of generate, check, adjust the configuration, then regenerate. Once you have your configuration the way you need, your SDKs are generated in seconds.

Adding more SDK languages is also fast - you add the new language to the configuration file, and regenerate.

liblab can also help you to keep your SDKs in sync with your API. As your API is updated, your SDK can be re-generated to match. For example, if your API spec lives in a git repository, you can set up a GitHub action to detect any changes, and regenerate your SDK, publishing the new SDK source code to your SDK repositories.

Finally liblab can generate your SDK documentation for you, with full code examples and all the documentation you need to get started. This is taken from your API specification, so is always in sync with your API.

creenshot from liblab UI indicating list pets and query attributes with an example of an SDK code and response fields creenshot from liblab UI indicating list pets and query attributes with an example of an SDK code and response fields

Conclusion

SDKs are a powerful way to improve the developer experience of your API. They come with a cost - the amount of work needed to generate them. This is why automation is so important. With liblab you can automate the process of generating SDKs, and keep them in sync with your API as it evolves.

Sign up for liblab today and start generating SDKs for your APIs in minutes.

← Back to the liblab blog

TL;DR - liblab can generate dev containers for your SDKs so you can start using them instantly. See our docs for details.

As software developers, our productivity is constantly increasing - with better tools, and even AI powered coding to allow us to deliver faster, and focus on building better solutions to more complex problems. The downside of this is the initial setup - getting our tools configured and our environments ready can be a big time sink. Anyone who has ever joined a new company with poor on-boarding documentation can attest to this! Days or even weeks trying to find the right versions of tools, and getting them configured correctly. It's almost a rite of passage for a new developer to re-write the onboarding document to add all the new tools and setup needed to get started.

This is something we see at liblab - our customers generate SDKs to increase their productivity, or the productivity of their customers, but to validate each SDK means setting up environments to run TypeScript, Java, Python. C#, Go and more. Although this is a one time cost, we decided to reduce this setup time so you can test out your generated SDKs in seconds - using dev containers!

What is a dev container?

A development container, or dev container, is a pre-configured isolated development environment that you can run locally or in the cloud, inside a container. Containers come with all the tools you need pre-installed, your code, and any configuration you need to get started, such as building or installing your code. They were designed to solve the setup problem as well as reliably deployments - set up your container once for a particular project, and everyone can share that setup. If the setup changes, the dev container changes, and everyone gets the new setup. It's also the closest thing we have to a "works on my machine" solution - if it works in the dev container, it will work for everyone. Literally like shipping your machine to your customers!

Running dev containers

Dev containers can be run locally through your favorite IDE, such as Visual Studio Code or IntelliJ, as long as you have container tooling installed such as Docker. You can also run containers in the cloud, using things like GitHub codespaces.

For example, you can create a dev container for Python development using one of your projects, that is based upon a defined version of Linux, has Python 3.11 installed, is configured to use the Python Visual Studio Code extension, and will install the required pip packages from your projects requirements.txt file when the container is created. As soon as you open this in Visual Studio Code, it will spin up the container, make sure the Python extension is installed, install your pip packages and you are instantly ready to start coding.

Dev containers isolation

Because dev containers are just that - containers, they run isolated from your local machine, so you don't need to worry about conflicting tool versions, or other conflicts. What is installed in the container just lives in the container, and what you have locally is not available inside that container. This means you can have multiple dev containers for different projects, and they won't conflict with each other. For example - you could have Python 3.11 installed locally, have one project in a dev container using Python 3.10 and another for legacy work using Python 2! Each will be isolated and have no idea about the other.

How are dev containers set up?

A dev container is defined by having a folder called .devcontainer in the root of your project. This folder contains a devcontainer.json file, which defines the container image to use, and any configuration you need to run your code. This devcontainer.json file can reference a pre-defined environment, such as Python, or NodeJS with TypeScript, or you can define your own environment using a Dockerfile.

.
└── .devcontainer/
└── devcontainer.json
└── Dockerfile

In the devcontainer.json file, you can also define any extensions you want to install in your IDE. By having the configuration in one or more files, these dev containers are instantly reproducible - check them into source code control and when someone else clones your repo and opens the folder, they will instantly get exactly the same environment.

You can read more on configuring dev containers in the dev container documentation.

How can I use dev containers with my generated SDK?

liblab can be configured to create the dev container configuration files for your SDK. This is done by an option in your configuration file:

{
...
"customizations": {
"devContainer": true
},
...
}

When you run the SDK generation process using liblab build, the generated SDK folder will come with the .devcontainer folder all ready to go. The container will be configured to not only install the relevant language tooling, but your SDK will also be installed ready to be used.

Use your dev container to test your SDK

To test your SDK in a dev container, make sure you have Docker desktop (or another Docker compliant container tool) running, and open the SDK folder for your language of choice in Visual Studio Code. You will be prompted to open the folder in a container, select Reopen in Container and your dev container will be created. This may take a few minutes the first time, but subsequent times will be much faster.

The VS Code reopen in container dialog

Let's use the dev container created with a Python SDK as an example. In this example, I'm going to use the Python SDK for our llama store API sample. Open this SDK in VS Code, or even open it in a codespace in GitHub.

Once the container is opened, a script is run to install the SDK dependencies, build the Python SDK as a wheel, then install this locally. There's no need to use a virtual environment, as the container is isolated from your local machine, so the installed wheel is only available in the container.

The output from the terminal showing the llama store SDK installed

As well as installing the SDK, the dev container will also install PyLance, the Python extension for Visual Studio Code, so VS Code will be fully configured for Python development. You can see this in the extensions panel:

The VS Code extensions panel with PyLance and the Python language server installed

This is now available from any Python code you want to run. Every SDK comes with a simple example - liblab takes the default get method and creates a small sample using this, and you can find this in the examples/sample.py file. If you open this file, you will see that VS Code knows about the SDK, with intellisense, documentation and code completion available:

The sample.py file with both code completion and documentation showing

It's now much easier to play with the SDK and build out code samples or test projects to validate your SDK before you publish it.

Conclusion

Dev containers are a great way to test out a new SDK. liblab can generate the dev container configuration for your SDK, so you can get started instantly. To find out more, check out our documentation.

← Back to the liblab blog

At liblab we generate software development kits, or SDKs, for your APIs. But what do we mean by 'SDK generation', and how does it work? This post explains everything you need to know about SDK generation, and how it can help you make your APIs more accessible.

What is SDK Generation?

Put simply, SDK generation is the process of automatically generating SDKs from an API specification. You have an API exposed using something like REST, and you want to make it easier for developers to access that REST API.

You could just let them access the API directly, but this relies on your user not only being experts in their own domains, but also knowing how to make REST calls, and to a certain degree the best practices for using your API. By creating an SDK, you are building a layer of abstraction over that API, embedding those best practices into the internals of the SDK code, and providing a nicer interface to your API in the programming languages that the developer is using.

In my experience, every team of developers that accesses APIs will always build some kind of layer of abstraction themselves. This will contain things like wrapper objects for the requests and responses to avoid using JSON, and service classes that wrap the REST requests in methods. These layers of abstraction may also include things like authentication, refreshing access tokens, retries, and error handling. This takes a lot of work, and is often not shared between teams in an enterprise who are all using the same API.

By auto generating an SDK, you can provide this layer of abstraction for your API, and ensure that all developers are using the same best practices. This cuts down on the boilerplate code being written, and allows developers to focus on solving real problems instead of wrapping JSON and REST. You don't write swathes of code, you use a tool that will do all the hard work for you, taking in your API and spitting out an SDK.

A machine that coverts APIs to SDKs

This auto generation also handles updates - add a new endpoint to your API? Regenerate the SDK, and the new endpoint will be available to your users. This means that your users will always have access to the latest version of your API, and you don't need to worry about them using an old version of your SDK.

Read more on a comparison between APIs and SDKs.

How Does SDK Generation Work?​

SDK generation is computers writing code for you. A tool takes an API specification, and generates code that can be used to access that API. The SDK code is generated in the programming languages of your choice.

REST API Validation​

Every generated SDK starts from an API specification. These use standards like OpenAPI to define the API - including the endpoints that can be called, and the expected data that will be sent as the request body, or the response of the call.

For example, your spec might have an endpoint called llama/{llama_id} that takes a llama Id in the URL, and returns a JSON object containing the details of that llama. The spec will define the URL, the HTTP method (GET), and the expected response body.

/llama/{llama_id}:
get:
tags:
- llama
summary: Get Llama
description: Get a llama by ID.
operationId: get_llama_by_id
parameters:
- name: llama_id
in: path
required: true
schema:
type: integer
description: The llama's ID
title: Llama Id
description: The llama's ID
responses:
'200':
description: Llamas
content:
application/json:
schema:
$ref: '#/components/schemas/Llama'
type: array
items:
$ref: '#/components/schemas/Llama'
title: Response 200 Get Llama By Id

The endpoints use schemas to define the objects that are sent or returned. In the example above, the response is defined as an array of Llama objects. The schema for a Llama object might look like this:

    Llama:
properties:
name:
type: string
maxLength: 100
title: Name
description: The name of the llama. This must be unique across all llamas.
age:
type: integer
title: Age
description: The age of the llama in years.
color:
allOf:
- $ref: '#/components/schemas/LlamaColor'
description: The color of the llama.
rating:
type: integer
title: Rating
description: The rating of the llama from 1 to 5.
id:
type: integer
title: Id
description: The ID of the llama.
type: object
required:
- name
- age
- color
- rating
- id
title: Llama
description: A llama, with details of its name, age, color, and rating from
1 to 5.

Before the SDK can be generated, the API needs to be validated. For example - the llama/{llama_id} endpoint returns a llama object defined using the #/components/schemas/Llama schema. If this doesn't exist, then the SDK cannot be successfully generated. The validation will also look for other things - for example, does the endpoint have operationId defined for each verb, which is used to generate the method name in the SDK. Are there descriptions for each endpoint, which can be used to generate the documentation for the SDK.

liblab can validate your API spec, and will give you a list of issues to resolve before you generate your SDK. The better your spec, the better your SDK will be.

SDK Generation

Once your API has been validated, the SDK can be generated. This is done by taking the validated API specification, and adding a sprinkle of liblab magic to generate the SDK code. This 'magic' is smart logic to build out model objects that match the requests and responses, as well as generating services that wrap the REST calls. The models handle missing fields in the responses, or patterns that are defined (such as ratings needing to be between 1 ans 5, or an email address field needing to be a valid email). The services implement required logic such as retrying failed requests, handling authentication, refreshing access tokens, and handling errors.

SDK generation also understands the programming language that you want to generate the SDK in. This means that the generated code will be idiomatic for that language. For example naming will be idiomatic to the language, so for the above llama example, the service will be called Llama in Python and C#, but the method to get a llama by Id will be get_llama_by_id in Python, and GetLlamaByIdAsync in C# - using snake case for Python and Pascal case for C#. The generated code will also use the idiomatic way of handling asynchronous calls - for example, in C# the generated code will use Task and async/await to handle asynchronous calls, naming them with the Async suffix.

A lot of the features generated in the SDK can be customized. For example, you can customize how retries are handled, including how many attempts and the time between retries. You can even hook into the API lifecycle and add custom logic to handle requests before they are sent, or responses before they are returned to the caller.

Documentation Generation​

As well as generating SDKs, liblab also generates documentation for the SDK from the validated API. This documentation not only shows how to call the API directly using tools like curl, but also code samples showing how to use the SDK. This way developers can literally copy and paste code examples from your documentation to get started quickly using your SDK.

This documentation is built using the descriptions and examples from the API spec, so the better the documentation in the spec, the better the documentation for the SDK. Your code samples will include these examples.

Packaging​

Its all very well to create an SDK, but you need to be able to store the code of your SDK somewhere, and distribute it to your users, and this is typically via a package manager like PyPi, NPM or NuGet. liblab generates all the relevant package manifest files, and can raise a pull request against your repository to add the generated SDK code. You can then review the PR, merge it, and publish the package to your package manager of choice, either a public package manager, or an internal one.

Best Practices For SDK Generation

Here are some best practices for SDK generation, to help you get the most out of your generated SDKs.

Understand Your Users’ Needs

The most important part of any software development process is:

Know thy user

Understand what your user needs. This might be their requirements for your SDK, or it will be your knowledge of how the SDK should work to give your users a seamless experience.

Generate for the users preferred programming languages

What programming languages are your users likely to use? For example, if you are developing for a large enterprise, chances are a C# and Java SDK might have a larger audience than a Go SDK. Smaller companies might be more likely to use Python or TypeScript.

Build for your users - and the big advantage of using SDK generation tools like liblab is growing the languages you support can be as simple as adding a new language to your config file, then packaging up the SDK for distribution to your users.

Simplify the Authentication Process

Authentication is hard, and everyone hates writing code to authenticate against an API. Make it easy for your users by handling authentication in the SDK. This might be as simple as providing a method to set the access token, or it might be more complex, such as handling the OAuth flow for your users by hooking into the API lifecycle.

SDKs can also handle refresh tokens, so if you want a persistent connection to your API, you can handle refreshing the access token in the SDK, and your users don't need to worry about it. This is very useful when writing server code that will run for months or even years on end, rather than desktop apps where the user will log in each day.

Have a good API spec

The old adage of 'garbage in, garbage out' applies here. If your API spec is not well defined, then the generated SDK will not be well defined.

Make sure you have tags and operation Ids defined, so the SDK services can be well named and grouped correctly - SDK generation uses the tag property to group endpoints into services, and the operationId to name the methods in the service (adjusting for different programming languages of course). For example, with this spec:

/llama:
get:
tags:
- llama
operationId: get_llamas
/llama_picture:
get:
tags:
- llama_picture
operationId: get_llama_pictures

This will give:

Service nameMethod name (Python)Method Name (C#)
llamaget_llamasGetLlamasAsync
llama_pictureget_llama_picturesGetLlamaPicturesAsync

Without these, the endpoints will be grouped into one service, and the names will be generated from the method and the URL, which might not give what you want.

For help on improving your OpenAPI spec, check out our Why Your OpenAPI Spec Sucks blog post.

Have Examples and descriptions

When coding, examples always help, giving developers something to start from when using a new SDK or library (the old joke about most code bring copied and pasted from Stack Overflow). The same applies to SDKs - if you have examples in your API spec, then these will be used to generate examples in the SDK documentation, and your users can copy and paste these examples to get started quickly.

Examples also help your users understand what data they should send to your API, and what they will get back. This is especially important for complex objects.

Descriptions are converted into code documentation, both in the SDK and in the docs that accompany it. These make it easier for your users to understand what the SDK is doing, and how to use it. In the example below, the documentation comes from the description in the API spec. The spec is:

APITokenRequest:
properties:
email:
type: string
title: Email
description: The email address of the user. This must be unique across all users.
password:
type: string
title: Password
description: The password of the user. This must be at least 8 characters long, and contain
at least one letter, one number, and one special character.

This gives the following documentation in your Python SDK:

A documentation popup for an APITokenRequest showing the descriptions of the email and password properties

Conclusion

SDKs make APIs more accessible for your users, and automatically generating SDKs makes it easier for you to provide SDKs for your APIs. liblab can help you generate SDKs for your APIs, and we can help you with the process of generating SDKs, and the best practices for doing so. Get in touch to find out more.