Skip to content

02Guides

Servers

Base URLs, per-operation servers and several clients.

An OpenAPI document lists the servers an API runs on, for the whole API and, if needed, for single paths or operations. swaggerz compiles the first top-level server into the client as its base URL, and sends operations that declare their own servers to theirs.

import { client } from './generated/api';
// At startup, for example from the environment the app runs in.
client.setConfig({ baseUrl: 'https://staging.example.com/api/v3' });

The compiled default is the specification’s first server with its variables replaced by their defaults; client.baseUrl in the config replaces it. Relative server URLs (/v1) of a specification loaded from a URL are resolved against that URL, as OpenAPI specifies, and a Swagger 2.0 document without host uses the host it was loaded from.

For environment-specific URLs, prefer setConfig at runtime over the compiled default: the generated code then stays identical across environments.

An operation (or path) with its own servers is sent to its first server, ignoring the client’s baseUrl:

paths:
/files/{name}:
servers:
- url: https://uploads.example.com
put:
operationId: uploadFile
import { uploadFile } from './generated/api';
const bytes = new Blob(['hello']);
await uploadFile({ name: 'hello.txt', body: bytes }); // PUT https://uploads.example.com/files/hello.txt
await uploadFile({ name: 'hello.txt', body: bytes }, { baseUrl: 'http://localhost:9000' }); // a per-call baseUrl wins

client.operationServers: false (in the config, or with setConfig at runtime) sends everything to the client’s base URL instead, for example to route all traffic through one proxy.

Create a client per base URL and pass it per call:

import { client, createClient, getPetById } from './generated/api';
const eu = createClient({ ...client.getConfig(), baseUrl: 'https://eu.example.com/api/v3' });
await getPetById({ petId: 10 }, { client: eu });
  • Only the first server of a list is used; there is no failover between servers.
  • Server variables are replaced by their defaults at generation time; to use another value, set the base URL at runtime.

What's generated

servers.yaml
openapi: 3.1.0
info:
title: Files
version: '1.0'
servers:
- url: https://api.example.com/v1
paths:
/files:
get:
tags: [files]
operationId: listFiles
responses:
'200':
description: The files.
content:
application/json:
schema:
type: array
items:
type: string
/files/{name}:
servers:
- url: https://uploads.example.com
put:
tags: [files]
operationId: uploadFile
parameters:
- name: name
in: path
required: true
schema:
type: string
requestBody:
required: true
content:
application/octet-stream:
schema:
type: string
format: binary
responses:
'204':
description: Stored.

files/upload-file.ts

/* eslint-disable */
// @generated by swaggerz. Do not edit: this file is overwritten on the next generation.
import { type RequestOptions, client } from '../client.js';
import { type ApiError, type RequestError, isApiError } from '../runtime/errors.js';
import type { HttpStatus } from '../runtime/types.js';
/** Request body of {@link uploadFile} (`application/octet-stream`). */
export type UploadFileBody = Blob | ArrayBuffer | ArrayBufferView;
/** Parameters of {@link uploadFile}. */
export type UploadFileParams = {
name: string;
/** Request body. */
body: UploadFileBody;
};
/** Response data of {@link uploadFile}. */
export type UploadFileResponse = void;
/** Body of an error response of {@link uploadFile}. */
export type UploadFileErrorBody = unknown;
/**
* The `ApiError`s {@link uploadFile} rejects with: one per documented status, so checking `status` narrows `body`.
*
* The last member covers statuses the specification does not document.
*/
export type UploadFileApiError = ApiError<unknown, HttpStatus<1 | 3 | 4 | 5>>;
/** Everything {@link uploadFile} rejects with: an `ApiError` for an error status, or a `RequestError` when no usable response arrived. */
export type UploadFileError = UploadFileApiError | RequestError;
/**
* Calls `PUT /files/{name}`.
*
* @remarks `PUT /files/{name}` (operationId `uploadFile`)
* @param params - Request parameters and body.
* @param options - Per-request options: `signal`, `timeout`, `headers`, `client`.
* @returns `204` Stored
* @throws {@link ApiError} When the server responds with a non-2xx status; narrow it with {@link isUploadFileApiError}.
* @throws {@link RequestError} When no usable response is received (network failure, timeout or invalid body).
*/
export function uploadFile(params: UploadFileParams, options?: RequestOptions): Promise<UploadFileResponse> {
return (options?.client ?? client).request<UploadFileResponse>(
{
operationId: 'uploadFile',
method: 'PUT',
path: '/files/{name}',
pathParams: { name: params.name },
body: params.body,
mediaType: 'application/octet-stream',
server: 'https://uploads.example.com',
},
options,
);
}
/** Whether `error` is an `ApiError` rejected by {@link uploadFile}. It narrows to {@link UploadFileApiError}, so checking `status` afterwards narrows `body` too. */
export function isUploadFileApiError(error: unknown): error is UploadFileApiError {
return (
isApiError(error) &&
error.operationId === 'uploadFile' &&
error.method === 'PUT'
);
}

client.ts

/* eslint-disable */
// @generated by swaggerz. Do not edit: this file is overwritten on the next generation.
import { createClient } from './runtime/client.js';
import { type FetchTransportOptions, fetchTransport } from './runtime/fetch.js';
import type { Client, RequestOptions as RuntimeRequestOptions } from './runtime/types.js';
/** Per-call options accepted by every generated operation. */
export type RequestOptions = RuntimeRequestOptions<FetchTransportOptions>;
/**
* The client used by generated operations.
*
* Configure it once at startup, for example:
*
* ```ts
* client.setConfig({ baseUrl: 'https://api.example.com', auth: { bearerAuth: () => getToken() } });
* ```
*
* Pass `{ client }` in the per-call options to use another instance created with `createClient()`.
*/
export const client: Client<FetchTransportOptions> = /* @__PURE__ */ createClient<FetchTransportOptions>({
baseUrl: 'https://api.example.com/v1',
transport: fetchTransport,
});
Generated by swaggerz 0.1.2, at build time.