Speakeasy Logo
Skip to Content

The API Key security scheme in OpenAPI

An API Key security scheme is the most common form of authentication for machine-to-machine APIs. It supports passing a pre-shared secret via the Authorization header (or another custom header), via a cookie, or as a query parameter.

The following examples demonstrate the three methods for passing an API key.

  • As a query string:

  • As a request header:

  • As a cookie:

Although the API Key security scheme is one of the most commonly used mechanisms, its security depends on the type of key used and how it was generated. Passing an API key via a header or cookie is often more secure than passing it via a query parameter, because logging mechanisms often store query param information.

The biggest security flaw is that most preshared secrets are long-lived, and if intercepted, can be used until they expire (generally in months or years) or are revoked. This risk is usually tolerated for machine-to-machine applications, as the chance of interception (especially when using private VPCs/TLS and other mechanisms) is relatively low compared to that of a key from a user’s device traveling on a public network.

Regardless of which method you use, using HTTPS or TLS is highly recommended.

Defining the API Key security scheme

The fields for an API Key security scheme are as follows:

Field
Type
String
Required
Description
Type
String
Required
Description
Human-readable information. This may contain CommonMark syntax  to provide a rich description.
Type
String
Required
Description
The location of the API key in the request. Valid values are
,
, or
.
Type
String
Required
Description
The name of the key parameter in the location.
Required
Description
Any number of extension fields can be added to the Security Scheme Object to be used by tooling and vendors.

To describe an API key, first create an object in securitySchemes with a name of your choosing. You can use ApiKey or even anythingYOULikeAuth, as long as it’s easy to remember and a valid YAML string. Then, define the object type as apiKey and define the name of the header, query, or cookie parameter as it should appear in the HTTP request:

You can add a description to let API users know where to find an API key or which email address to contact to request one.

Using multiple API keys

Some APIs require two API keys to be used at once. For example, users may need to use an app ID and an app key simultaneously. In such cases, define both keys as securitySchemes, then reference them both in the same Security Requirement Object.

Last updated on