Skip to content

Get started

Sign up, create an API key, create a practice and send your first order to the Affinity API.

Updated View as Markdown

Affinity sends compounded prescriptions from platforms and practices to pharmacies. You send an order to Affinity. Affinity sends it to the pharmacy and tells you when its status changes.

  • A platform is software that orders for many practices. It uses the API.
  • A practice is a customer organization. An independent practice can use the API to order for itself.

Platform and independent practice keys can read accounts and medications, and create, read and cancel orders. Only platform keys can create and manage child practices.

The API has few parts:

Part Endpoints Guide
Practices POST /v1/practices, GET /v1/practices Practices
Medications GET /v1/medications Choose a medication
Orders POST /v1/orders, GET /v1/orders, cancel Send an order
Order updates POST /v1/webhook-endpoints and signed webhook events Receive order updates

Get an account

Use one of the last two major versions of Chrome, Edge, Firefox or Safari. This includes Safari on iOS. Older browser versions are not supported.

Use an email address with at most 128 characters. It must use only ASCII characters. For example, use name@example.com. If Affinity cannot use an address, sign-in or the invitation shows an error at the email field.

  1. Open the Affinity app.
  2. Sign in with your email address and the code that Affinity emails you.
  3. Select the type of organization:
    • If your software sends orders through the Affinity API for many practices, select Platform.
    • If you order medications for your patients, keep Practice.
  4. If your account has no name yet, enter your first name and your last name.
  5. Enter the name of the platform or the practice. For a practice, also enter its phone number, street address, city, state and ZIP code.
  6. Click Create platform or Create practice.

An organization that you create starts with Live access. Test needs no payment method and sends no order to a real pharmacy. A Live order needs a payment method on file. Add a card or a bank account in Settings → Billing. Read Test and Live mode, and IDs to learn more about Live.

Create a Test API key

You must be an admin of a platform or an independent practice.

  1. Sign in to the Affinity app.
  2. Open the account menu at the bottom left. Select Settings → API.
  3. Select the Test tab. The page can open on Live for an organization with Live access.
  4. Click New API key.
  5. Enter a name for the key.
  6. Click Create key.
  7. Copy the key and keep it on your server. The app shows the key one time only. If you lose it, create a new key.

A Test key starts with sk_test_. A Live key starts with sk_live_. Each key acts for its organization and mode.

Replace or revoke a key

A key has no permission scopes. It can call every public API route available to its organization and mode. Dashboard-only routes, including key, member and organization management and sending

webhook test events, return 403 dashboard_only. Only an admin can manage keys.

  • To rename a key, select its name in Settings → API.
  • To revoke a key, delete it in Settings → API. Requests that use the key fail at once with 401 unauthorized. Affinity cannot restore a deleted key.
  • To rotate a key, create a new key and put it in your server configuration. Check that the old key shows no new use under Last used. Then delete the old key.

If a key leaks, delete it first, then create a new key. Then tell support@affinityrx.com.

A key belongs to the organization, not to the person who created it. When you remove a member, their keys continue to work. If the person had a copy of a key, rotate that key.

Make a request

Send these headers with each request:

Header Value
Authorization Bearer and your API key.
Affinity-Version 2026-11-01. Read Versions.
Idempotency-Key A new value for each write. Read Retry safely.
Content-Type application/json, when the request has a body.

The x-affinity-api-key header is still accepted but deprecated. Use Authorization: Bearer <key> instead. Bearer takes precedence if both headers are sent, even when the Bearer credential is invalid.

Read your account to test the key:

curl https://api.affinityrx.com/v1/account \
  -H "Authorization: Bearer $AFFINITY_API_KEY" \
  -H "Affinity-Version: 2026-11-01"
const apiKey = process.env.AFFINITY_API_KEY;
const response = await fetch("https://api.affinityrx.com/v1/account", {
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Affinity-Version": "2026-11-01",
  },
});
if (!response.ok) {
  const { code, detail, requestId } = (await response.json()) as Record<string, string>;
  throw new Error(`${code}: ${detail} (request ${requestId})`);
}
const account = await response.json();

The response names your organization and the mode of the key:

{
  "id": "plat_01j9z3k4m5n6p7q8r9s0t1v2w4",
  "type": "platform",
  "name": "Example Health",
  "phone": null,
  "address": null,
  "mode": "test",
  "liveEnabled": false,
  "createdAt": "2026-10-28T15:04:05.000Z"
}

The TypeScript examples use the built-in fetch of Node.js 20 or later, Bun or Deno. They need no packages. Run them on your server. Each example reads the key from the AFFINITY_API_KEY environment variable.

An error response has a JSON problem body. The examples read its code, detail and requestId. Make decisions on code. Give the requestId to Affinity support. To retry a write, use the function in Retry safely.

TypeScript types

Types are optional. To type requests and responses, generate them from the OpenAPI document with openapi-typescript:

npx openapi-typescript https://docs.affinityrx.com/openapi.json -o affinity.d.ts

Then select a response or a request body from paths:

import type { paths } from "./affinity";

type Account = paths["/v1/account"]["get"]["responses"][200]["content"]["application/json"];
// For a request body, use
// paths["/v1/orders"]["post"]["requestBody"]["content"]["application/json"].

const apiKey = process.env.AFFINITY_API_KEY;
const response = await fetch("https://api.affinityrx.com/v1/account", {
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Affinity-Version": "2026-11-01",
  },
});
if (!response.ok) {
  const { code, detail, requestId } = (await response.json()) as Record<string, string>;
  throw new Error(`${code}: ${detail} (request ${requestId})`);
}
const account = (await response.json()) as Account;

Rate limits

Each API key averages 25 requests each second on each API server, with bursts of up to 50. The count is separate on each

server. A request over the limit returns 429 rate_limit_exceeded with a Retry-After header. The header gives the number of seconds to wait. Wait for Retry-After, then send the same request again with the same Idempotency-Key. A 429 can also mean that too many of your requests are in progress at the same time. This count includes Test and Live requests together. A platform and the practices that it manages share one count, so a practice can get 429 while its platform sends many Test requests. Do the same steps. Responses do not include headers that give the remaining request budget, because each server counts separately. Use Retry-After to pace your requests.

Do not retry a 429 at once in a loop. A client that sends more than 20 requests with an invalid API key in one minute from one address also gets 429.

Retry safely

A network error or a timeout does not tell you whether Affinity did the action. Send each write with an Idempotency-Key header. When you get no answer, send the request again with the same key and the same body. Affinity does the action once.

RequestIdempotency-Key
POST /v1/feedback Required
POST /v1/orders Required
POST /v1/orders/{orderId}/cancel Required
POST /v1/practices Required
PATCH /v1/practices/{practiceId} Required
POST /v1/webhook-endpoints Required
PATCH /v1/webhook-endpoints/{webhookEndpointId} Required
POST /v1/webhook-endpoints/{webhookEndpointId}/resend-failed Required
  • A key has 1 to 255 printable ASCII characters and no spaces, for example a UUID. Another value, or a missing required key, returns 400 invalid_request.
  • Use a new key for each new action. Keys are separate for each organization and mode, and for each request and record: the same key on another request, or on the cancel of another order, does not replay.
  • A replay does not repeat the action. POST /v1/orders and POST /v1/orders/{orderId}/cancel return the first response’s status code with the order as it is now. Webhook endpoint creation rebuilds the creation response from the endpoint and original request, including the signing secret within the key’s lifetime. It returns 404 not_found after the endpoint is deleted. The secret is not stored in the idempotency record. Other keyed requests return the first response.
  • The same key with a different body returns 409 idempotency_key_reused.
  • A retry that arrives while the first request still runs waits for it, then replays it. While the first request still sends to an outside service, the retry returns 409 request_in_progress. Wait, then send it again with the same key.
  • A request that Affinity refused with 400 or 422 does not use up its key. Correct the body and send it again.
  • Affinity keeps a key for 24 hours after the first request. After that, the same key is a new request. An order’s key stays longer while the order is submitted or processing or its cancel is waiting.

For orders, also send an externalOrderId: a second order with an externalOrderId that the practice already used returns 409 order_already_exists with the existing order ID.

A 5xx response, a network error or a timeout can occur after Affinity did the action. Retry a keyed write in this sequence. Use the same sequence for 409 request_in_progress:

  1. Wait. Double the wait before each retry (for example 1, 2, then 4 seconds) and add a random delay of up to 1 second. If the response has a Retry-After header, wait for that number of seconds instead.
  2. Send the same request with the same Idempotency-Key and the same body.
  3. Stop after 3 retries.
  4. For an order, read GET /v1/orders?externalOrderId=<your ID>&practiceId=<the order's practiceId> to see whether one of the tries created it. Send the practiceId of the order request: another practice can use the same externalOrderId. Read Find an order by your ID. If no order is there, send the request again later with the same key and body. If the error continues, give Affinity support the requestId.

This TypeScript function does steps 1 to 3. You give it the request one time. Each try sends that request again, with the same Idempotency-Key and the same body:

/**
 * Sends a keyed write. Retries a network error, a 429, a 5xx
 * and a 409 request_in_progress.
 */
async function sendWithRetry(url: string, init: RequestInit) {
  for (let retry = 0; ; retry++) {
    let response: Response | undefined;
    try {
      response = await fetch(url, init);
    } catch (error) {
      if (retry === 3) throw error;
    }
    if (response?.ok) return response.json();
    const problem = (await response?.json().catch(() => undefined)) as
      Record<string, string> | undefined;
    const again =
      !response ||
      response.status === 429 ||
      response.status >= 500 ||
      problem?.code === "request_in_progress";
    if (response && (!again || retry === 3)) {
      const { code, detail, requestId } = problem ?? {};
      throw new Error(`${code}: ${detail} (request ${requestId})`);
    }
    const retryAfter = Number(response?.headers.get("Retry-After"));
    const seconds = retryAfter > 0 ? retryAfter : 2 ** retry + Math.random();
    await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
  }
}

const apiKey = process.env.AFFINITY_API_KEY;
const order = await sendWithRetry(
  "https://api.affinityrx.com/v1/orders/ord_01j9z3k4m5n6p7q8r9s0t1v2w7/cancel",
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Affinity-Version": "2026-11-01",
      "Idempotency-Key": crypto.randomUUID(),
    },
  },
);

Affinity compares parsed bodies after input decoding: object key order and JSON spacing do not matter, but array order matters. Omission, explicit defaults and null can differ; preserve the same body, including no body, and use a separate key for each practice.

For orders, omitted externalOrderId, middleName, notes, compoundingReason and daysSupply compare as null; an omitted apartment line also becomes null. Blank middleName, notes and compoundingReason also compare as null. Phones, states and ZIP codes compare in their stored form. Practice names, address lines and city names compare after trimming; blank apartment lines compare as null. For bodyless actions, no body and {} compare alike. Other bodies are refused.

Input formats

Send US phones, states and ZIP codes in the form you have. Affinity stores one form, and responses and webhooks return it.

Field You can send Affinity stores
Phone +15125550100, +1 512 555 0100, (512) 555-0100, 512-555-0100, 512.555.0100, 5125550100 or 1 (512) 555-0100 +15125550100
State TX, tx or Tx TX
ZIP code 78701, 78701-1234, 78701 1234 or 787011234 78701 or 78701-1234

A phone has 10 digits, with or without +1 or 1 before them. Spaces, dashes, dots and parentheses can separate the digits. Every digit is allowed. Affinity refuses letters, other country codes, extensions and phones longer than 40 characters. Remove an extension before you send the phone. Affinity never removes part of a number.

For optional text, such as middleName, address.line2, notes and compoundingReason, and for optional phones, empty text or text with only spaces is null. Required text needs at least one visible character. A blank externalId or externalOrderId is refused: omit it or send null. Affinity removes spaces around dateOfBirth and an NPI. Send the date as YYYY-MM-DD; Affinity reads no other date format.

These checks test format only; they do not confirm phone service, address delivery or a ZIP/state match.

Unknown query parameters and fields in a declared request body return 400 invalid_request. Remove them before sending again.

A malformed path ID returns 400 invalid_request. A well-formed unknown ID returns 404 not_found.

Versions

Send Affinity-Version: 2026-11-01 with each request. A missing or unknown version returns 400 unsupported_api_version.

Version 2026-11-01 changes only in ways that keep your integration working:

  • New endpoints.
  • New optional request fields.
  • New response fields and webhook payload fields.
  • New values in a list of values in a response or a webhook event, such as order and prescription status, error code, medication category and requirements, and allergy category.
  • New event types. Read the event type before you decode the event into a typed model, and skip a type that you do not know. See receive order updates.

Ignore fields that you do not know. A new shipping destination type comes only in a new version. A rename, a removal or a change of meaning comes only in a new version, and Affinity announces the date before it removes an old version.

Create a practice

A platform orders for its practices, so a platform creates a practice before its first order. An independent practice uses its own account ID and skips this step.

curl https://api.affinityrx.com/v1/practices \
  -H "Authorization: Bearer $AFFINITY_API_KEY" \
  -H "Affinity-Version: 2026-11-01" \
  -H "Idempotency-Key: get-started-practice-42" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "Example Practice",
    "phone": "+15125550123",
    "address": {
      "line1": "200 Example Ave",
      "line2": "Suite 4",
      "city": "Austin",
      "state": "TX",
      "postalCode": "78701"
    }
  }'
const apiKey = process.env.AFFINITY_API_KEY;

/** Creates one practice. To retry it, send the same practice with the same saved key. */
async function createPractice(practice: object, idempotencyKey: string) {
  const response = await fetch("https://api.affinityrx.com/v1/practices", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Affinity-Version": "2026-11-01",
      "Idempotency-Key": idempotencyKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(practice),
  });
  if (!response.ok) {
    const { code, detail, requestId } = (await response.json()) as Record<string, string>;
    throw new Error(`${code}: ${detail} (request ${requestId})`);
  }
  return response.json();
}

// Make the key one time. Save it with your practice record before the first request.
const idempotencyKey = crypto.randomUUID();
const practice = await createPractice(
  {
    name: "Example Practice",
    phone: "+15125550123",
    address: {
      line1: "200 Example Ave",
      line2: "Suite 4",
      city: "Austin",
      state: "TX",
      postalCode: "78701",
    },
  },
  idempotencyKey,
);

Keep the id in the response. It starts with prac_. Send it as practiceId in each order for this practice. Read Practices.

Send a first order

  1. Choose a medication and read its quantities, compounding reasons and shipping options.
  2. Send an order with POST /v1/orders. The request creates the order, signs it for the prescriber and sends it to the pharmacy.
  3. Receive order updates to follow the order to delivery.

Test and Live

The key sets the mode. A Test key reads and writes Test records only. A Live key reads and writes Live records only. The API address is the same for both modes. Read Test and Live mode, and IDs.

Report a problem

For help with an order, an integration or a security problem, email support@affinityrx.com. Give the order ID or the requestId when you have one. Each response has its request ID in the X-Request-Id header. An error response also has it in the body as requestId. Affinity replies within one business day.

If a response or a page is wrong or unclear, send POST /v1/feedback with an Idempotency-Key, a short message and the requestId from the response. Do not include patient information. API-key callers can send 10 submissions per hour per key. Anonymous callers can send 10 submissions per hour per IP address.

Next steps

  1. Practices. Create the practices that your platform orders for.
  2. Choose a medication. Find a medication and read what its pharmacy accepts.
  3. Send an order. Create, sign and submit an order with one request.
  4. Receive order updates. Add a webhook endpoint and verify each event.
  5. Find and cancel orders. List orders, read shipments and cancel an order.
  6. Test and Live mode, and IDs. Learn how Test orders behave and how to go Live.
Navigation

Send feedback

Don't include patient information.

Type to search…

↑↓ navigate ↵ select Esc close