alepha@docs:~/docs/.content/release/framework/docs/guides/server$
cat 12-third-party-api.md | pretty
4 min read
Last commit:

#In Front of a Third-Party API

An Alepha web module often sits in front of an API it does not own: a backend written by another team, in another language, described by an OpenAPI document. $client and $remote do not apply there. They take their types from an import type of an Alepha controller and resolve paths through /api/_links, which a foreign API does not serve.

What applies is HttpClient, the outbound client every Alepha call already goes through, and a few habits around it. This page is the recipe: there is no $api primitive and Alepha generates no client (see No generated clients).

#The call

Wrap the API in a service, one method per endpoint, each with a zod schema for its response:

typescript
 1import { $inject, z } from "alepha"; 2import { HttpClient } from "alepha/server"; 3  4const customerSchema = z.object({ 5  id: z.text(), 6  name: z.text(), 7  email: z.text().optional(), 8}); 9 10export class CustomerApi {11  protected readonly http = $inject(HttpClient);12  protected readonly base = "https://api.example.com";13 14  async get(id: string) {15    const { data } = await this.http.fetch(16      `${this.base}/customers/${encodeURIComponent(id)}`,17      { schema: { response: customerSchema } },18    );19    return data; // { id: string; name: string; email?: string }20  }21 22  async rename(id: string, name: string) {23    await this.http.fetch(`${this.base}/customers/${encodeURIComponent(id)}`, {24      method: "PATCH",25      headers: { "content-type": "application/json" },26      body: JSON.stringify({ name }),27    });28  }29}

What HttpClient.fetch gives such a call:

  • A typed, validated response. With schema.response the body is decoded through the schema: the type is inferred from it, and a response that does not match fails at the boundary instead of three components later. Without a schema the data is untyped.
  • Cancellation. On the server the call runs under the request's signal, so a visitor who leaves stops the calls their page made (Cancellation).
  • A timeout. 30 seconds by default on the server, timeout per call, and the httpClientOptions atom for the whole app.
  • Errors. A 4xx or 5xx rejects with an HttpError carrying the status and the API's own message, whether it answered JSON or text.
  • A client span per call when tracing is on.

The path, the query and the body are not typed: they are strings and RequestInit, as fetch takes them. The method is where they get a type.

#A large surface

For an API with hundreds of endpoints, writing a schema per response is work worth skipping where the response is only displayed. Types derived from the API's OpenAPI document (with a generator of your choice, run in your own build) plug in at the same place: the service method's signature.

typescript
 1import { $inject } from "alepha"; 2import { HttpClient } from "alepha/server"; 3  4// What a generator writes from the OpenAPI document, reduced to one path. 5interface paths { 6  "/invoices/{id}": { 7    get: { response: { id: string; total: number; currency: string } }; 8  }; 9}10 11type Invoice = paths["/invoices/{id}"]["get"]["response"];12 13export class InvoiceApi {14  protected readonly http = $inject(HttpClient);15 16  async get(id: string): Promise<Invoice> {17    const { data } = await this.http.fetch(18      `https://api.example.com/invoices/${encodeURIComponent(id)}`,19    );20    return data as Invoice;21  }22}

⚠️ Such types are compile-time only. Nothing checks that the API answered what its document says: the cast above is a promise, not a proof. Pass a schema.response where a wrong shape would do harm (money, permissions, anything written back), and keep the cast for what is only shown.

A typed client library of your choice works the same way: call it from the service, and hand it Alepha's signal and timeout so it stops with the request.

#From a page

A page loader runs on the server for the first render and in the browser on navigation; both call the same service.

tsx
 1import { $inject, z } from "alepha"; 2import { $page } from "alepha/react/router"; 3import { HttpClient } from "alepha/server"; 4  5const customerSchema = z.object({ id: z.text(), name: z.text() }); 6  7class CustomerApi { 8  protected readonly http = $inject(HttpClient); 9 10  async get(id: string) {11    const { data } = await this.http.fetch(12      `https://api.example.com/customers/${encodeURIComponent(id)}`,13      { schema: { response: customerSchema } },14    );15    return data;16  }17}18 19export class AppRouter {20  protected readonly customers = $inject(CustomerApi);21 22  customer = $page({23    path: "/customers/:id",24    schema: { params: z.object({ id: z.text() }) },25    loader: async ({ params }) => ({26      customer: await this.customers.get(params.id),27    }),28    component: ({ customer }) => <h1>{customer.name}</h1>,29  });30}

Data a component fetches after the page rendered goes through useQuery, which gives it a key, cancellation on unmount and the app's error toaster (React):

tsx
 1import { $inject, z } from "alepha"; 2import { useInject, useQuery } from "alepha/react"; 3import { HttpClient } from "alepha/server"; 4  5const orderSchema = z.array(z.object({ id: z.text(), total: z.number() })); 6  7class OrderApi { 8  protected readonly http = $inject(HttpClient); 9 10  async list(customerId: string, signal?: AbortSignal) {11    const { data } = await this.http.fetch(12      `https://api.example.com/customers/${encodeURIComponent(customerId)}/orders`,13      { schema: { response: orderSchema }, signal },14    );15    return data;16  }17}18 19export const Orders = (props: { customerId: string }) => {20  const orders = useInject(OrderApi);21  const query = useQuery(22    {23      key: ["orders", props.customerId],24      handler: ({ signal }) => orders.list(props.customerId, signal),25    },26    [props.customerId],27  );28  return (29    <ul>30      {query.data?.map((order) => (31        <li key={order.id}>{order.total}</li>32      ))}33    </ul>34  );35};

#Through the app's own origin

When the browser calls the API itself, CORS and a second origin come with it. A $proxy puts the API under the app's own origin instead:

typescript
 1import { $proxy } from "alepha/server/proxy"; 2  3export class Gateway { 4  api = $proxy({ 5    path: "/api-proxy/*", 6    target: "https://api.example.com", 7    rewrite: (url) => { 8      url.pathname = url.pathname.replace("/api-proxy", ""); 9    },10    timeout: [10, "seconds"],11  });12}

By default the proxy sends neither Cookie nor Authorization upstream: the session's cookie and its access token stay with the app. An API that authenticates the caller from the same token says so with forward: ["authorization"]; an API that takes a service token instead gets it from beforeRequest. websocket: true forwards a WebSocket upgrade too. See Credentials stay home.

#Per environment

The API's address differs between staging and production. Declare it as an env key the browser may read, and one build serves both:

typescript
 1import { $env, $inject, z } from "alepha"; 2import { HttpClient } from "alepha/server"; 3  4export class CustomerApi { 5  protected readonly http = $inject(HttpClient); 6  protected readonly env = $env( 7    z.object({ 8      CUSTOMER_API_URL: z.text({ 9        browser: true,10        description: "Base URL of the customer API.",11      }),12    }),13  );14 15  async get(id: string) {16    const { data } = await this.http.fetch(17      `${this.env.CUSTOMER_API_URL}/customers/${encodeURIComponent(id)}`,18    );19    return data;20  }21}

The server reads it from its environment; the browser gets the same value, in the page's head or in config.js for a static site. A key without browser: true never leaves the server. See Reading a variable in the browser.

#In tests

MemoryHttpClient answers the API's routes in a spec, records every call and refuses an unexpected one. Only the transport is replaced: the schema, the timeout and the error mapping run as they do against the network.

typescript
 1import { $inject, Alepha, z } from "alepha"; 2import { HttpClient, MemoryHttpClient } from "alepha/server"; 3import { describe, expect, it } from "vitest"; 4  5class CustomerApi { 6  protected readonly http = $inject(HttpClient); 7  8  async get(id: string) { 9    const { data } = await this.http.fetch(10      `https://api.example.com/customers/${id}`,11      { schema: { response: z.object({ id: z.text(), name: z.text() }) } },12    );13    return data;14  }15}16 17describe("CustomerApi", () => {18  it("reads a customer", async () => {19    const alepha = Alepha.create().with({20      provide: HttpClient,21      use: MemoryHttpClient,22    });23    const http = alepha.inject(MemoryHttpClient);24    http.on("GET", "https://api.example.com/customers/:id", ({ params }) => ({25      id: params.id,26      name: "Ada",27    }));28 29    const customer = await alepha.inject(CustomerApi).get("c1");30 31    expect(customer).toEqual({ id: "c1", name: "Ada" });32    expect(33      http.calls("GET", "https://api.example.com/customers/:id"),34    ).toHaveLength(1);35  });36});

Error statuses, network failures and latency are simulated per route. See External APIs.