Guide to servers object handling
OpenAPI 3 has a servers
property that can be used to define the base url for the whole document, or
specific operations. This guide aims to explain how this is processed.
You can find the specifications definition of the servers object here
This is fully supported, including placeholder/variable substitution, and overriding.
The servers object is only used for client SDK templates.
It doesn’t really make sense in the context of a server template, and so is ignored.
Overview
Consider an example servers block:
servers:
- url: '{protocol}://{host}:{port}'
variables:
host:
default: localhost
protocol:
enum: [http, https]
default: http
port:
default: '8080'
It defines a single server, with three variables.
This will generate a ApiClientServers
object that you can use to create a basePath
like so:
const client = new ApiClient({
// basePath will be https://localhost:80
basePath: ApiClientServers
.server("{protocol}://{host}:{port}") // the url template determines the build function
.build(
"https", // string literal union to form the enum
undefined, // pass undefined to take the default
"80", // override defaults
)
})
If you pass no args to build, the defaults from the specification are used:
const client = new ApiClient({
// basePath will be http://localhost:8080
basePath: ApiClientServers
.server("{protocol}://{host}:{port}")
.build()
})
You can also take the default (first) server like so:
const client = new ApiClient({
// basePath will be http://localhost:8080
basePath: ApiClientServers
.server()
.build()
})
Operation specific overrides
You can specify servers
overrides at the path, or individual operation level. The most specific servers
block
will be used for a given operation.
For example, override the url for all operations under the /attachments
route:
paths:
/attachments:
servers:
- url: 'https://attachments.example.com'
When overrides are specified, an additional basePath
positional argument will be added to the operation, defaulting
to the first overridden server
with default placeholder values.
export class ApiClient {
async uploadAttachment(
p: { ... },
// Overridden server param
basePath:
| Server<"uploadAttachment_ApiClient">
| string = ApiClientServers.operations
.uploadAttachment()
.build(),
timeout?: number,
opts: RequestInit = {},
): Promise<Res<202, void>> {
...
}
}
As you can see the overrides for each operation are exposed as ApiClientServers.operations.<operationId>()
following
the same pattern as the root servers.
Configuration
This behavior is optional, and be turned off by passing:
--enable-typed-base-paths=false
When disabled basePath: string
parameters will still be added to operations that have a servers
override, but
no code based on the url
or variables
will be generated.
See also CLI reference