# how-to-build-sdks
Source: https://speakeasy.com/blog/how-to-build-sdks


import { Callout, Table } from "@/mdx/components";

## Why SDKs Matter for Developer Adoption

An SDK can be a game-changer for accelerating developer adoption and streamlining integration. Without one, developers are left to decipher API documentation that might lack essential information or be disorganized, and then build each API call by hand. This means handling everything from authentication and request construction to response parsing, error handling, retries, pagination, and beyond—a process that significantly complicates and delays integration.

In contrast, a well-designed SDK lets developers get started in minutes by importing a single library. Features like in-IDE auto-completion and type safety prevent integration bugs before they happen. Advanced tasks like rate limiting or pagination become seamless. The result is a smooth, even delightful developer experience that fosters trust in your API.

Established API-first companies—Stripe, Plaid, Twilio—prove the point. Their client SDKs provide an A+ developer experience, helping them dominate in their respective markets.

## Developer Experience Without vs. With an SDK

The value of an SDK becomes crystal clear when you compare the integration process with and without one. Let's contrast the developer experience:

```typescript filename="Manual API Integration"
// Without SDK - Complex manual implementation
async function getUser(userId: string): Promise<User> {
  try {
    const response = await fetch(`https://api.example.com/v1/users/${userId}`, {
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
    });

    if (!response.ok) {
      if (response.status === 429) {
        // Implement rate limiting logic
        await sleep(calculateBackoff(response.headers));
        return getUser(userId);
      }
      throw new Error(`API error: ${response.status}`);
    }

    const data = await response.json();
    // Manual type validation
    if (!isValidUser(data)) {
      // Check for required fields, data types, etc.
      throw new Error("Invalid user data received");
    }
    return data;
  } catch (error) {
    // Complex error handling
    if (shouldRetry(error)) {
      // e.g., check for network errors
      await delay(calculateBackoff()); // Exponential backoff strategy
      return getUser(userId);
    }
    throw error;
  }
}

// Implementing pagination
async function listUsers(): Promise<User[]> {
  const allUsers = [];
  let page = 1;

  while (true) {
    const response = await fetch(
      `https://api.example.com/v1/users?page=${page}`,
      { headers: { Authorization: `Bearer ${apiKey}` } },
    );

    const data = await response.json();
    allUsers.push(...data.users);

    if (!data.hasNextPage) break;
    page++;
  }

  return allUsers;
}
```

With a well-designed SDK, however, developers can get started in minutes by simply importing the library:

```typescript filename="SDK Integration"
// With SDK - Clean, type-safe interface
const client = new APIClient({
  apiKey: process.env.API_KEY,
});

// Simple request with built-in error handling
const user = await client.users.get(userId);

// Automatic pagination handling
for await (const user of client.users.list()) {
  console.log(user.name);
}
```

The difference is dramatic. An SDK transforms complex, error-prone implementation details into simple, intuitive method calls. It handles the heavy lifting of authentication, error handling, rate limiting, and pagination behind the scenes, allowing developers to focus on building their applications rather than wrestling with API integration details.

To dive deeper into why SDKs are crucial for API adoption and developer experience, [check out our comprehensive guide on APIs vs SDKs.](/post/apis-vs-sdks-difference)

## Comparing SDK Development Options

When it comes to building SDKs for your API, you have three main routes. Each comes with specific costs, maintenance burdens, and control levels:

<Table
  columns={[
    { key: "handwritten", header: "Handwritten" },
    { key: "openSource", header: "Open Source" },
    { key: "speakeasy", header: "Speakeasy" },
  ]}
  data={[
    {
      handwritten: "✅ Full DevEx control",
      openSource: "✅ No upfront cost",
      speakeasy: "✅ Up‐to‐date, idiomatic code aligned with best practices",
    },
    {
      handwritten: "✅ Unlimited custom code",
      openSource:
        "❌ Feature gaps for common API features (OAuth 2.0, pagination, retries)",
      speakeasy: "✅ Strong DevEx control",
    },
    {
      handwritten: "✅ Aligned with internal coding style",
      openSource: "❌ Non‐idiomatic code hurts DevEx",
      speakeasy: "✅ Custom code support",
    },
    {
      handwritten: "❌ High cost (~\\$90K per SDK)",
      openSource: "❌ No CI/CD integration",
      speakeasy: "✅ Automated publishing",
    },
    {
      handwritten: "❌ Upfront cost per language",
      openSource: "❌ High operational costs",
      speakeasy: "✅ Docs integration",
    },
    {
      handwritten: "❌ Requires diverse in-house language expertise",
      openSource: "❌ Requires OpenAPI spec",
      speakeasy: "✅ Full ownership of code",
    },
    {
      handwritten: "❌ Slow API feature updates",
      openSource: "❌ Slow maintenance (4,000+ open GitHub issues)",
      speakeasy: "❌ Paid solution",
    },
    {
      handwritten: "❌ No automated documentation",
      openSource: "❌ Major customization limitations",
      speakeasy: "❌ Requires OpenAPI spec",
    },
    {
      handwritten: "*",
      openSource: "*",
      speakeasy: "❌ Small customization limitations",
    },
  ]}
  rowKeyField="format"
/>

### Hand-Written SDKs

Building SDKs by hand offers maximum control over the developer experience and allows for perfect alignment with internal coding styles. However, this approach comes with significant trade-offs. The initial development cost is high (around $90,000 per SDK), and ongoing maintenance requires a dedicated team with expertise in multiple programming languages. Beyond the direct costs, several common pitfalls can undermine the success of hand-written SDKs:

1.  **Neglected Maintenance:** APIs evolve. If your SDK doesn't evolve alongside it, you'll introduce breaking changes, outdated docs, and dissatisfied users.
2.  **Inconsistent Language Support:** If you release multiple SDKs but treat one as a “primary” language, users in other languages may feel neglected.
3.  **Improper Error Handling:** Failing to handle retries, rate limits, or authentication seamlessly can turn a developer's first impression sour.
4.  **Over-Engineering or Under-Engineering:** Trying to build a “perfect” SDK can lead to months of development. Conversely, a bare-bones approach can frustrate users with missing features.
5.  **Incomplete Documentation:** Even the best SDK is useless if developers can't find clear examples and usage instructions.

---

### Using OpenAPI Generator

OpenAPI Generator is a robust, open-source tool that automates the creation of SDKs from your OpenAPI specifications. Distributed under the Apache 2.0 license, it offers the flexibility to modify and integrate the generated code into commercial projects across multiple languages. Its straightforward setup and integration with CI/CD pipelines make it an attractive option for teams focused on rapid prototyping or projects with narrowly defined requirements.

That said, while the tool boasts a low upfront cost, it comes with a set of challenges that can become significant in production environments. For instance, as of January 2024, the repository was burdened with over 4,500 open GitHub issues—a stark indicator of the ongoing community maintenance challenges and the absence of formal support or SLAs. This reliance on community-driven fixes can result in unpredictable resolution times for critical bugs or regressions, making it a less-than-ideal choice for enterprise applications.

Moreover, the quality and idiomatic correctness of the generated code can vary widely between target languages. Developers may find themselves investing considerable time customizing templates, patching bugs, and integrating advanced features like OAuth flows, rate limiting, or webhooks to meet internal standards and production-grade requirements. This hidden engineering overhead can quickly erode the initial cost savings offered by the tool.

While OpenAPI Generator remains a viable solution for projects with very specific needs or constraints—particularly where time-to-market is paramount—its challenges in maintenance, support, and consistency often prompt larger organizations to consider more comprehensive, enterprise-grade alternatives.

For a deeper dive into these challenges and a detailed comparison with Speakeasy's managed approach, [read our analysis.](/post/speakeasy-vs-openapi-generator)

---

### Speakeasy

Speakeasy generates enterprise-grade SDKs directly from your OpenAPI spec, eliminating the need for a proprietary DSL or additional config files.

**Key Benefits**:

- **Fully Managed & Always Up-to-Date:** Automated validation, code generation, publishing, and regeneration upon API spec changes.
- **OpenAPI-Native & No Lock-In:** Uses your existing OpenAPI spec as the single source of truth.
- **Idiomatic & Enterprise-Ready:** Generates code that feels native to each language, with built-in authentication, retries, pagination, and error handling.
- **Automated Testing & Documentation:** Ensures SDK compatibility and provides comprehensive API references.
- **Dedicated Support:** A professional team to handle fixes, new features, and improvements.

<Callout type="neutral">
  "Finding Speakeasy has been transformational in terms of our team's velocity. We've been able to progress our roadmap faster than we thought possible. We were able to get SDKs for 3 languages in production in a couple of weeks!"

— Codat Engineering Team

</Callout>

---

## Making the Right Choice

Your decision hinges on **resources, timeline,** and **feature demands**:

- **Hand-Written SDKs:** Maximum control, but at the highest cost and longest development time.
- **OpenAPI Generator:** A seemingly free option, but often requires significant hidden engineering effort for maintenance and customization.
- **Speakeasy:** The fastest and most cost-effective way to get enterprise-grade, fully-managed SDKs, directly from your OpenAPI spec.

Building SDKs is a significant investment in your API's success, but the right approach can dramatically impact both your costs and adoption rates. Speakeasy offers a compelling alternative to traditional methods, providing enterprise-grade SDKs without the usual time and cost burden.

Because Speakeasy is OpenAPI-native, you maintain complete control of your API definition. Generate your first SDK in minutes using your existing OpenAPI spec, or work with our team to optimize it for the best possible results.

[Click here](https://app.speakeasy.com/) to generate your first SDKs — for free.