10 Best Practices For SDK Generation

10 Best Practices For SDK Generation

Posted in

When evaluating a new product or service, it doesn’t take much to make a developer abandon ship and look elsewhere. They don’t want to spend an hour installing libraries and dependencies — that’s a textbook definition of a bad developer experience. Instead, they want to give the tool a quick spin and see how it fits into their existing stack and workflow.

This is where SDKs come in.

SDKs, or Software Development Kits, give developers everything they need to try out a new tool like an API in one place. Despite their popularity and usefulness, there’s been a lack of centralized standards and best practices for SDK generation. This inspired APIMatic, an API documentation tool that lets you autogenerate SDKs, to create an SDK Knowledge Center, SDKs.io.

We’ve been poring over SDKs.io in search of best practices for creating SDKs. We also asked Sid Maestre, VP of Developer Relations for APIMatic, to share some tips and best practices for building SDKs, which we’ll share along with our own findings.

1. Consider the Developer

The first step in creating any digital product is understanding your audience. Before you begin developing an SDK, it’s important to understand your users and their needs. This will inform everything from what programming languages to include in your SDK to the use cases you might cover in your code snippets.

As part of preparing their SDK knowledge base, APImatic performed a large-scale analysis of a wide range of SDKs and the companies that use them. According to Maestre, “Go is growing in popularity and is only a few steps behind C# in popularity. 94% of the companies we looked at support JavaScript developers through either a JavaScript or TypeScript SDK.”

If you’re unsure what languages to include in your SDK, Go, C#, JavaScript, and TypeScript are good places to start.

2. Stick With a Naming Convention

Consistent naming conventions make your SDKs easy to use and understand. It also helps your SDK to be self-descriptive, so users can use it without having to consult the documentation. For example, it’s a good idea to adhere to the best practice of adopting camelcase for your naming conventions.

When creating assets in your SDK, it’s recommended to aim for 30 characters or less so they don’t become too unwieldy. It’s recommended to follow common best practices for naming resources, like creating actions with the ‘verb + object/resource’ format, such as getUsers. It’s also recommended to follow the best practices for naming conventions in APIs, like using singular nouns for individual assets and plurals for groups or classes like getDog vs. getDogs, for example.

For more insights, check out the Naming Conventions section of SDKS.io.

3. Reduce Authentication Complexity

SDKs offer an opportunity to simplify the authentication process. APIs use various authentication methods, ranging from HTTP to API access tokens to 0Auth. You can use your SDK to streamline the authentication for developers.

Here’s an example of how a developer might manage API authentication using an SDK:

DefaultClient defaultClient = new DefaultClient();
defaultClient.init("foo", "bar");

ApiClient apiClient = new ApiClient(defaultClient);

// listUsers handles setting the authorization header automatically
List<User> users = apiClient.listUsers();

4. Transform Endpoints Into SDK Methods

Transitioning your API endpoints into methods is another best practice for creating SDKs that allows developers to quickly and intuitively understand how to use your SDK. Furthermore, it’s a good idea to group related actions together to prevent one method from getting too large while still keeping the number of classes that need to be initialized to a minimum.

SDK methods are reusable code for performing a specific action. They typically are comprised of one request and at least one response, behaving very similarly to an API endpoint. When translating an API into an SDK, it’s a recommended best practice to transform your API endpoints into SDK methods to help keep the primary code DRY (don’t repeat yourself) as well as adaptable.

SDK methods can be used to perform a number of common actions performed by API endpoints, ranging from validating arguments to constructing URLs based on query parameters. They’re also useful for working with HTTP, letting you set HTTP verbs and execute HTTP requests quickly and easily. SDK methods can also make your API more efficient and streamlined, as they can be used to deserialize responses and return them as native objects.

Some common API endpoints for SDK methods include:

  • Validate argument(s)
  • Set header(s)
  • Construct URL with query parameters
  • Set HTTP verb
  • Serialize request body
  • Set Credentials (token, username/password)
  • Build and execute HTTPRequest
  • Deserialize response
  • Return response as a native object

Here’s an example of what a method for constructing a URL written in Java might look like:

UriBuilder uriBuilder = UriBuilder.fromUri({baseURL} + "/Contacts");

//handle query parameters with the following line of code
//uriBuilder = uriBuilder.queryParam(key, value);

String url = uriBuilder.build().toString();
GenericUrl genericUrl = new GenericUrl(url);

//Serialize the contact model into JSON for our HTTP request

HttpContent content = helperClass.new JacksonJsonHttpContent(contact);

5. Define Data Models

When an SDK defines a data model, it can greatly simplify the process of working with API data by following a well-defined approach to deserializing JSON responses. Data models can provide autocomplete support for IDEs as well as help monitoring tools catch any potential issues.

Data models can include information about what type of data will be transmitted, like whether it’s a number, string, or boolean. It can also include information about data properties, like its name or any constraints it might have. This all makes consuming an API much more efficient.

6. Include Logging

Including a logging solution with your SDK will let developers know how your API is performing. It will include any error messages, debug messages, or notable events that occur during the execution of a code.

Including a logging solution helps developers to identify and fix issues more efficiently. It also helps them identify areas that could be improved, such as bottlenecks. It can also record usage patterns, which can be used to identify security issues and see how people use your products.

Logging solutions can be included with an SDK by including a built-in library or by integrating with an external logging framework like Log4j or Serilog.

7. Establish a Persistent HTTP Connection

An HTTP connection involves resolving the DNS of a server, establishing a TCP connection, and performing a TLS handshake to ensure the connection is secure. Performing this series of steps each time a query is made greatly increases latency time.

Persistent HTTP connections let developers make multiple HTTP requests through a single HTTP connection. Persistent connections are the default for HTTP/1.1 clients, but HTTP/1.0 clients need to be specified with the “Connection: keep-alive” request header.

Here’s an example of an HTTP client for establishing a persistent HTTP connection in Python, as shared on SDKs.io:

import requests

# Create a session object to reuse the connection
session = requests.Session()

# Set the keep-alive header to enable persistent connections
session.headers.update({'Connection': 'keep-alive'})

# Define the API endpoint URL
url = 'https://api.example.com'

# Define the payload for the API call
payload = {'key': 'value'}

# Make the API call using the session object
response = session.post(url, json=payload)

# Process the API response
if response.status_code == 200:
   data = response.json()
   # Process the API response data
else:
   # Handle API errors

8. Include Code Snippets

Maestre recommends including idiomatic code examples as part of your SDK. “Writing idiomatic code will also have a big impact on the usability of your SDK. Idiomatic code refers to a style of programming that adheres to the conventions and best practices of a particular programming language. It follows the established norms of the language and is considered natural or intuitive by experienced programmers. You wouldn’t want to use Java conventions in a Python library — it would place unnecessary cognitive work on the developer trying to understand unfamiliar patterns.”

Seeing practical examples of code implementation is an essential step in helping developers get started with an API.

9. Consider Automated SDK Generation

Automated SDK generation helps eliminate some of the problems you might encounter when creating SDKs. If you’re updating your SDK manually, for instance, you might overlook some revisions to your API, breaking your SDK in the process. It also greatly reduces the time, energy, and resources needed for creating an SDK.

Speaking on the benefits of automated SDK generators, Maestre says, “Your API specification becomes the source of truth for building your SDKs, documentation, code samples, and other artifacts. Therefore, updates to your API specification can be quickly rolled out into multiple SDKs.”

10. Consider If an SDK Is Necessary

For all their many benefits, including an SDK isn’t always necessary. SDKs.io lists a number of reasons why your API might not need an SDK, ranging from limited users to a simplistic API format. Maeetre doesn’t catastrophize about not including an SDK with an API, but he does strongly advocate for the practice. “It’s more of a missed opportunity than a risk,” says Maestre, when asked about the risks of not including an SDK with an API.

He goes on to list some of the many benefits of including an SDK with a new tool or product. “With SDKs, you can provide production-ready code samples that developers can leverage to build integrations faster. Getting started guides and tutorials can include code snippets written with your SDKs. Also, you reduce the number of basic questions your support team needs to field.”

Final Thoughts On SDKs

SDKs make it easy for developers and users to get started with your API right out of the box. They address any potential problems and initial difficulties users might encounter before they occur. SDKs allow users and developers to get right to it, plugging your API into their workflow and giving it a test drive.

Considering that a huge majority of [=public APIs, and tech products in general, have some sort of freemium tier, SDKs seem like another vital step in converting users into customers (and getting an audience in the first place). If you’re trying to reach as wide of an audience as possible and build a loyal user base, you’d be wise to consider offering an SDK with your API.