EDDYMENS

Published 5 months ago

How To Override The Base URL For A Specific Endpoint In An OpenAPI Spec

Most APIs share the same base URL [→] with different paths [→] tacked on.

For instance, https://example.com/category and https://example.com/posts both start with the base URL https://example.com, while /category and /posts are the unique paths respectively.

When documenting your APIs using the OpenAPI Specification [↗], you typically set the base URL globally, which is then applied to all endpoints defined in the spec.

To set this globally, you define the servers property outside the paths section. Here's how it looks:

line 19:11 [→] is where we define our base URL.

Global Definition Example

01: openapi: 3.0.3 02: info: 03: title: Simple OpenAPI template 04: description: | 05: Simple open API template 06: license: 07: name: Apache 2.0 08: url: http://www.apache.org/licenses/LICENSE-2.0.html 09: version: 1.0.11 10: servers: 11: - url: https://example.com/api/v1 12: tags: 13: - name: v1 14: description: Simple API (v1) 15: 16: paths: 17: ...

Setting a Custom Base URL

But what if you have one endpoint with a different base URL? Or perhaps all endpoints except one have a different version number? For example:

01: https://example.com/api/v1/user 02: https://example.com/api/v1/users 03: https://example.com/api/v2/users

In the list of URLs above, you'll notice that the first two share the same version number (v1), while the latter is set to v2. Ideally, we'd upgrade all APIs to v2 and document these new endpoints as a separate API specification. However, in the real world, we might not have that luxury. So, let's assume we need to document everything in the same specification.

The OpenAPI specification allows you to set a base URL under a specific path, which will override the global base URL:

Base URL Override

01: ... 02: paths: 03: /users: 04: servers: 05: - url: "https://example.com/api/v2" 06: ...

In this example, the global base path applies to all endpoints except the one where a specific base URL has been defined.

Here is another article you might like 😊 What Is A Request Body?