Skip to content

Adapter Pattern: Fit a Third-Party SDK Into Your Own Interface

Learn the Adapter pattern by wrapping a vendor SMS SDK behind the interface your code already uses, with TypeScript, Python and PHP examples.

11 min readDesign patternStructural

Convert the interface of an existing class into the interface its clients expect, so classes with incompatible interfaces can work together without changing either of them.

Adapter is the pattern you reach for when two pieces of code are each fine on their own but disagree about how they talk. Most of the time one side is code you cannot or should not change: a vendor SDK, a legacy module, a generated client. You write a small class that speaks your interface on the outside and the foreign interface on the inside. This guide follows one invented case: a pharmacy chain moving its prescription-ready text messages to a new SMS vendor without touching the code that sends them. Interviewers like Adapter because it tests whether you can separate your domain from someone else's API, and whether you can say where the translation belongs.

The problem

A situation where the obvious design starts to hurt.

Greenleaf Pharmacy runs 40 stores and sends about 12,000 text messages a day telling patients their prescription is ready. The notification code depends on one small interface, SmsSender, with a single method: send(phoneE164, text) returns a message id string and throws SmsDeliveryError on failure. Phone numbers are stored in E.164 format, like +447700900123.

Procurement has signed a cheaper contract with a vendor called TextBolt. Its SDK looks nothing like SmsSender. The method is transmit(countryCode, localNumber, body): the country code is a separate integer, the number has no plus sign or country prefix, and instead of throwing it returns a result object with an ok flag, a numeric ticket and an optional error code.

The obvious fix is to edit every call site: the prescription notifier, the refill reminder job and the delivery-slot confirmations. That spreads TextBolt's quirks through the codebase, means three places to fix if TextBolt changes its SDK, and makes switching vendors again just as painful. Editing the SDK itself is not an option; it is vendor code that gets replaced on every upgrade.

The solution

What the pattern proposes.

Write one class, TextBoltSmsAdapter, that implements SmsSender and holds a reference to a TextBoltClient. When the notifier calls send("+447700900123", text), the adapter splits the number into country code 44 and local number 7700900123, calls transmit, checks the ok flag, throws SmsDeliveryError if TextBolt rejected the message, and otherwise returns an id built from the ticket, such as tb-9001.

The notifier never learns that TextBolt exists. It is still constructed with an SmsSender, and the only change in the application is the line that wires dependencies together: pass a TextBoltSmsAdapter instead of the old sender.

All knowledge about the vendor lives in one file. If TextBolt adds a required field, renames a method or changes its error codes, you edit the adapter. If Greenleaf switches vendors again next year, you write another adapter and leave the rest of the system alone.

An everyday analogy

The same idea, outside software.

Think of a sign language interpreter at a press conference. The speaker talks the way they always do, and the deaf audience watches signing the way they always do. Neither side learns the other's language or changes how it communicates. The interpreter listens in one form and produces the same meaning in another, sometimes restructuring sentences because the grammar differs. Swap in a different interpreter for a different language and the speaker's speech stays exactly the same.

Structure

The pieces and how they relate.

PrescriptionNotifier depends only on SmsSender; TextBoltSmsAdapter implements it and translates calls to the vendor's TextBoltClient.PrescriptionNotifier calls SmsSender (send()). RelaySmsSender implements SmsSender. TextBoltSmsAdapter implements SmsSender. TextBoltSmsAdapter has a TextBoltClient (transmit()).PrescriptionNotifierclient code«interface»SmsSendersend(phoneE164,text): stringRelaySmsSenderold vendor, alreadycompatibleTextBoltSmsAdaptersend(): splitsnumber, maps errorsTextBoltClienttransmit(cc, local,body): ResultVendor SDKthird-party code,never editedsend()transmit()
PrescriptionNotifier depends only on SmsSender; TextBoltSmsAdapter implements it and translates calls to the vendor's TextBoltClient.

Participants

Target (SmsSender)
The interface your code already depends on. It is defined in your terms: E.164 numbers in, a string id out, exceptions on failure.
Client (PrescriptionNotifier)
Code that uses the Target. It is built against SmsSender and is unaware which vendor sits behind it.
Adaptee (TextBoltClient)
The existing class with a useful but incompatible interface. Here it is a third-party SDK you cannot change.
Adapter (TextBoltSmsAdapter)
Implements the Target and wraps an Adaptee instance. Translates arguments, return values and error conventions in both directions.

Pseudocode

The solution to the scenario, language-neutral.

interface SmsSender
    method send(phoneE164, text): string

// vendor SDK, not ours
class TextBoltClient
    method transmit(countryCode: int, localNumber, body): TransmitResult

class TextBoltSmsAdapter implements SmsSender
    field client: TextBoltClient
    const SUPPORTED_CODES = ["353", "44"]

    method send(phoneE164, text)
        (code, local) = splitNumber(phoneE164)
        result = client.transmit(code, local, text)
        if not result.ok
            throw SmsDeliveryError(result.error)
        return "tb-" + result.ticket

    method splitNumber(phone)
        if phone does not start with "+" then throw SmsDeliveryError
        digits = phone without "+"
        for code in SUPPORTED_CODES
            if digits starts with code
                return (toInt(code), digits after code)
        throw SmsDeliveryError("unsupported country")

class PrescriptionNotifier
    field sms: SmsSender
    method notifyReady(phone, patient, store)
        return sms.send(phone, "Hi " + patient + ", your prescription is ready at " + store + ".")

// composition root: the only place that knows about TextBolt
notifier = new PrescriptionNotifier(new TextBoltSmsAdapter(new TextBoltClient()))

The code

The same solution in TypeScript, Python and PHP.

// Target: the interface Greenleaf's code depends on
interface SmsSender {
  send(phoneE164: string, text: string): string;
}

class SmsDeliveryError extends Error {}

// Adaptee: simplified stand-in for the TextBolt vendor SDK
interface TransmitResult {
  ok: boolean;
  ticket: number;
  error?: string;
}

class TextBoltClient {
  private nextTicket = 9000;

  transmit(countryCode: number, localNumber: string, body: string): TransmitResult {
    if (body.length > 459) {
      return { ok: false, ticket: 0, error: "BODY_TOO_LONG" };
    }
    this.nextTicket += 1;
    console.log(`[TextBolt] +${countryCode} ${localNumber}: ${body}`);
    return { ok: true, ticket: this.nextTicket };
  }
}

// Adapter
class TextBoltSmsAdapter implements SmsSender {
  private static readonly COUNTRY_CODES = ["353", "44"];

  constructor(private readonly client: TextBoltClient) {}

  send(phoneE164: string, text: string): string {
    const { countryCode, localNumber } = this.splitNumber(phoneE164);
    const result = this.client.transmit(countryCode, localNumber, text);
    if (!result.ok) {
      throw new SmsDeliveryError(`TextBolt rejected message: ${result.error}`);
    }
    return `tb-${result.ticket}`;
  }

  private splitNumber(phone: string): { countryCode: number; localNumber: string } {
    if (!phone.startsWith("+")) {
      throw new SmsDeliveryError(`Not an E.164 number: ${phone}`);
    }
    const digits = phone.slice(1);
    for (const code of TextBoltSmsAdapter.COUNTRY_CODES) {
      if (digits.startsWith(code)) {
        return { countryCode: Number(code), localNumber: digits.slice(code.length) };
      }
    }
    throw new SmsDeliveryError(`Unsupported country: ${phone}`);
  }
}

// Client
class PrescriptionNotifier {
  constructor(private readonly sms: SmsSender) {}

  notifyReady(phone: string, patientName: string, storeName: string): string {
    const text = `Hi ${patientName}, your prescription is ready at ${storeName}.`;
    return this.sms.send(phone, text);
  }
}

const notifier = new PrescriptionNotifier(new TextBoltSmsAdapter(new TextBoltClient()));
console.log(notifier.notifyReady("+447700900123", "Priya", "Greenleaf Camden"));
console.log(notifier.notifyReady("+353851234567", "Sean", "Greenleaf Galway"));
try {
  notifier.notifyReady("+15550100", "Dana", "Greenleaf Camden");
} catch (e) {
  console.log((e as Error).message);
}

When to use it

Situations where it pays off.

  • You want to use an existing class, often a third-party SDK, but its interface does not match the one the rest of your code relies on.

    The adapter absorbs the mismatch in one place, so your domain code keeps its own vocabulary and does not import vendor types.

  • You expect to swap vendors or run two providers side by side, for example TextBolt in the UK and another gateway elsewhere.

    Each provider gets its own adapter behind the same interface, and choosing one becomes a wiring decision instead of an edit across the codebase.

  • You are integrating a legacy module you are not allowed or not ready to refactor.

    An adapter lets new code depend on a clean interface today while the legacy internals stay untouched until you can replace them.

  • You want to unit test code that talks to an external service.

    Because the client depends on your interface rather than the SDK, tests can pass a fake SmsSender without mocking vendor classes.

How to implement it

Steps to introduce it in existing code.

  1. Define the Target interface from the client's point of view: the method names, argument types and error behaviour your code wants, not what the vendor offers.

  2. List every difference between the Target and the Adaptee: argument shapes (one E.164 string versus country code plus local number), return types (string id versus result object) and error style (exceptions versus status flags).

  3. Create the adapter class, implement the Target interface and accept the Adaptee through the constructor so it can be replaced or faked.

  4. Implement each Target method by translating inputs, calling the Adaptee, and translating outputs and failures back into your own types and exceptions.

  5. Keep vendor-specific types inside the adapter. Nothing it returns or throws should be a TextBolt class.

  6. Change only the composition root to construct the adapter, and add tests for the translation rules such as number splitting and error mapping.

Pros and cons

What you gain and what you pay.

Pros

  • Single Responsibility: the translation between your model and the vendor's lives in one class instead of being scattered across call sites.
  • Open/Closed: you can add a new provider by writing a new adapter without modifying existing client code.
  • Client code stays independent of the SDK, which keeps vendor upgrades and vendor switches contained.
  • Easy to test: clients take a fake Target in tests, and the adapter itself can be tested against a stubbed Adaptee.

Cons

  • Adds a class and a layer of indirection, which is unjustified if you control both sides and could simply align the interfaces.
  • Mismatches in capability cannot be hidden forever: if the vendor lacks a feature your interface promises, the adapter has to emulate it or fail.
  • A thin adapter over a large SDK can grow into a second, hand-maintained API that must track every vendor release.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between an object adapter and a class adapter?

An object adapter holds a reference to the adaptee and delegates to it, as TextBoltSmsAdapter does. A class adapter inherits from the adaptee and implements the target at the same time, which needs multiple inheritance or an adaptee that is safe to subclass. Object adapters are the default answer: they work with final SDK classes, can wrap any subclass of the adaptee, and keep the vendor's public methods off your interface.

Adapter or Facade: how do I explain the difference in an interview?

Ask who owns the interface. With Adapter, the client already has an interface it expects and you make an existing class conform to it. With Facade, you design a new, simpler entry point over a complicated subsystem. In the Greenleaf case SmsSender existed before TextBolt arrived, so wrapping TextBolt is an adapter, even if it also simplifies things.

Should the adapter do anything beyond translating calls?

Keep it to translation: argument shapes, return types, units, error conventions. Retries, rate limiting, caching and logging are separate concerns and fit better in decorators around SmsSender or in dedicated resilience components. Mixing them into the adapter makes it harder to test and harder to reuse when you add a second vendor.

Why not just pass TextBolt's result object back to the caller?

Because then every caller learns about ok, ticket and TextBolt error codes, and the vendor's model leaks into your domain. Mapping failures to your own SmsDeliveryError and returning a plain id means a future vendor only has to honour the same contract inside a new adapter.

Is it worth writing an adapter if I only have one vendor?

Often yes for external SDKs, because it gives you a test seam and keeps vendor types out of business code. It is not worth it when you own both sides and could simply rename a method, or when the SDK already matches your interface; then the adapter is a pass-through that adds nothing.

Next guide2 of 7 · Structural patternsBridge Pattern: Split Abstraction from ImplementationRead the next one