Skip to main content

OpenAPI CodeGen Extensions

OpenAPI/Swagger (v2.0, v3.x) facilitates third-party vendors to implement tool-specific extensions. These extensions allow customizing behaviors beyond simple API definitions. We at APIMatic also offer extensions that are specific to Code Generation and can be specified within your OpenAPI definition file. These extensions allow you to customize the APIMatic code generation engine as per your requirements. The following documentation discusses the extensions available and how to use them.

Code Generation Settings and OpenAPI Extensions

In the case of Swagger/OpenAPI, we provide extensions that you can use within your OpenAPI definition to specify code generation settings and get the desired customizability. We also provide similar extensions for API Blueprint whose details can be viewed at API Blueprint Extensions. The extensions are supported by both the "Import" API operation, as well as by our Code Generation as a Service API.

CodeGen Extensions and How To Use Them

We offer the following CodeGen extensions:

  1. Advanced Settings for Endpoints
  2. Additional Headers
  3. Basic Authentication Extensions
  4. OAuth 2.0 Extensions
  5. Discriminator Value Extension
  6. Enumeration Extensions
  7. Datetime Extensions
  8. Dynamic Response Extension
  9. Exception Model Name Extension
  10. Example Extensions
  11. API Metadata Extensions
  12. API Filtering Roles Extension
  13. Applied Authentication Options Extension

Advanced Settings

APIMatic allows further customization of endpoints (called operations in OpenAPI) through the Advanced Settings extensions. These extensions can be specified inside the Operation Object (v2, v3).

Two extensions are currently available which are defined below:

  1. Operation Settings
  2. Multiple Body Parameters Setting
  3. Deprecation Details
  4. Overriding Parameter Names

Operation Settings

These settings are specified using property name x-operation-settings. See an example as follows:

"paths": {
"/pets": {
"post": {
...
"operationId": "addPet",
"x-operation-settings": {
"collectParameters": false,
"allowDynamicQueryParameters": true,
"allowDynamicFormParameters": false,
"isMultiContentStreaming": false,
"methodName": "create",
"groupName": "pets",
"forceRetries": true
}
}
}
}

Details of the properties available within this extension are given below:

PropertyTypePurpose
collectParametersBooleanWhen true, this operation's parameters are expected to passed as a collection. For example in PHP, the generated method expects a Map containing parameters as Key-Value pairs. This is currently implemented for PHP, Python, GO, and Objective-C.
useModelPostfixBooleanWhen true, a postfix "Model" is appended to all classes generated from schemas.
allowDynamicQueryParametersBooleanWhen true, the generated method has an additional Map input, which may contain dynamic number of query parameters as Key-Value pairs.
allowDynamicFormParametersBooleanWhen true, the generated method has an additional Map input, which may contain dynamic number of form parameters as Key-Value pairs.
isMultiContentStreamingBooleanWhen true, it indicates that this operation is a streaming endpoint. For example, Twitter Streaming API endpoints.
parameterCollectionNameStringRepresents the name of the model that represents CollectedParameters.
methodNameStringWhen specified, it's used instead of the operation name (extracted from the operation ID/summary) for generating method names in SDKs. While an operation ID in OpenAPI needs to be unique across the complete API, the method name should ideally be unique among all operations in a particular path item only.
responseMappingResponse Mapping ObjectResponse mapping strategy to use for mapping the HTTP response to the result passed to the endpoint caller in an SDK. This will override the response mapping specified in the CodeGen settings if any.
groupNameStringWhen specified, it's used for generating the endpoint's group name in SDKs/docs instead of the first tag name specified in an Operation object.
forceRetriesBooleanWhen set to true, the SDKs can force retry an endpoint regardless of whether it's idempotent or not. If false, the endpoints won't be retried. By default, only idempotent endpoints are retried.
errorTemplatesMap [String, String]Custom-templated messages that can be provided for overriding default exception messages thrown in SDKs for error responses. More details can be found here. Note, that an error template specified at operation level will override the one specified under CodeGen settings for the same error template key.
skipAdditionalHeadersBooleanWhen set to true, any additional headers applied at API level will be ignored for the current endpoint. This is set to false by default.

Multiple Body Parameters Setting:

Since OpenAPI doesn't allow defining multiple body parameters, you can use this setting to help unwrap any body parameter into multiple body parameters for Code Generation purposes. Essentially, this setting is a boolean flag specified using the name x-unwrap-body inside the Operation object. You can simply define a schema in the OpenAPI/Swagger file (generally inside #/definitions or #/components/schemas depending on the OAS/Swagger version) where schema fields will represent the body parameters. Link this schema in the body parameter definition of the Operation object and set the flag to true. We will then automatically unwrap the body schema into multiple body parameters during the import process.

A usage example of the flag described above is shown below:

"post": {
"summary": "Multiple body parameters",
"parameters": [{
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/bodySchema"
}
}],
"x-unwrap-body": true
}

Here the schema fields of bodySchema represent the actual body parameters.

Deprecation Details:

This extension can be used inside the Operation object using key x-deprecation-details. This extension allows you to define additional details for your operation if it has been declared as deprecated using the OAS deprecated property. The properties available for describing the deprecated operation in more detail are:

PropertyTypePurpose
messageStringHelps describe any additional information about the deprecated operation for example reason, alternative, etc.
deprecatedInVersionStringHelps specify the version in which this item was deprecated.

A usage example of the above extension is given below:

"post": {
...
"operationId": "addPet",
"summary": "Deprecated operation",
"deprecated": true,
"x-deprecation-details": {
"message": "This operation is deprecated. Use createPet",
"deprecatedInVersion": "2.0"
}
}

Overriding Parameter Names

To enhance the usability and clarity of parameter names in your SDKs and API documentation, you can use the parameter-level extension x-unique-name. This extension allows you to:

  1. Resolve Duplicate Names: Provide a unique secondary name for parameters that share the same name, ensuring clarity in the Code and API portal.
  2. Simplify Long or Unfriendly Names: Replace overly lengthy or technical parameter names with a user-friendly alternative, improving the overall developer experience.
Key Considerations
  • The name specified in x-unique-name must not conflict with any existing parameter names in the API.
  • This secondary name is only used for display purposes in the Code and API portal and doesn't alter the actual API calls or their behavior.
Example

Here's an example of how to use x-unique-name:

parameters:
- name: id
in: query
required: true
schema:
type: string
x-unique-name: userId
- name: id
in: path
required: true
schema:
type: string
x-unique-name: orderId

In the example above:

  • Both id parameters are distinguished using x-unique-name as userId and orderId in the Code and API documentation.
  • API consumers will see these friendly names in the SDKs and the portal, but the actual parameter name remains id for API requests.

This extension ensures your Code and API documentation is intuitive and developer-friendly without impacting the technical implementation.

Additional Headers:

APIMatic allows defining global headers that are sent with every API call using the Addition Headers extension. These headers are in addition to any headers required for authentication or defined as parameters. These headers can be specified inside the Security Scheme Object (v2, v3) using property name x-additional-headers. See an example below:

"securityDefinitions": {
"basicAuth": {
"type": "basic",
"x-additional-headers": [
{
"name": "api-version",
"description": "The version number indicator for the API",
"default": "1.1"
},
{
"name": "sdk-version",
"description": "The version number indicator for the SDK",
"default": "1.1.0.1"
}
...
]
}
}

An additional header is defined using a subset of the properties of the Parameter Object (v2, v3). The available properties are:

PropertyTypePurpose
nameStringName of the header
descriptionStringAny details regarding the header
defaultStringAny default value for the header

Basic Authentication Extensions

By default, basic authentication requires username and password as input parameters. If you need to override the names of these parameters for code generation, you can use the extensions described below:

ExtensionTypeDescription
x-rename-username-asStringThe alternate name for username parameter for example name
x-rename-password-asStringThe alternate name for password parameter for example secret

Both the above extensions can be used inside the Security Scheme Object (v2, v3) as follows:

"securityDefinitions": {
"basicAuth": {
"type": "basic",
"x-rename-username-as": "name",
"x-rename-password-as": "secret"
}
}

OAuth 2.0 Extensions:

APIMatic also offers several extensions to help you configure your OAuth 2.0 security definition. For v2.0, you can use these extensions inside the Security Scheme Object and for v3.x inside the OAuth Flow Object as follows:

"securityDefinitions": {
"oauth2": {
"type": "oauth2",
"flow": "password",
"tokenUrl": "http://example.com/tokenurl",
"x-skip-client-authentication": false,
"x-oauth2-clientid-example": "clientid",
"x-oauth2-clientsecret-example": "clientsecret",
"x-oauth2-username-example": "username",
"x-oauth2-password-example": "password"
}
}

The detailed explanation of all these extensions is given below:

ExtensionTypeDescriptionApplicable to Flows
x-skip-client-authenticationBooleanThe OAuth 2.0 flow of resource owner password credentials will normally involve client app authentication using Client Id and Client Secret. However, if you want to skip this authentication for Code Generation purposes, you can set its value to truepassword
x-oauth2-clientid-exampleStringSpecifies a value that can be used as an example or demo client ID*password, implicit, application, accessCode
x-oauth2-clientsecret-exampleStringSpecifies a value that can be used as an example or demo client secret*password, implicit, application, accessCode
x-oauth2-username-exampleStringSpecifies a value that can be used as an example or demo client usernamepassword
x-oauth2-password-exampleStringSpecifies a value that can be used as an example or demo client passwordpassword
x-allow-additional-oauth-fieldsBooleanWhen enabled, allows additional properties return in OAuth 2.0 flows.password, implicit, application, accessCode
x-additional-oauth-fieldsObjectSpecifies an object of properties returned in OAuth 2.0 flow.password, implicit, application, accessCode
*

The extension isn't applicable to flow password if x-skip-client-authentication is set to true.

Discriminator Value Extension

OpenAPI makes use of a property discriminator to support polymorphism in custom types. As per OpenAPI, the value of this property must be the name of the parent model or the children models depending on which type the object represents. However, we allow our users to specify a custom discriminator value using the APIMatic's Discriminator Value extension. This value will override the default custom type name.

Usage

The extension is used through the x-discriminator-value property.

PropertyTypePurpose
x-discriminator-valueStringCustom discriminator value

For OpenAPI 1.2, the extension can be used inside the Model Object while for 2.0, it can be used inside the Definitions Object. In case of OpenAPI 3.x, the extension can be used inside the Discriminator Object. All of this is illustrated in the examples below:

"Pet": {
"id": "Pet",
"required": [
"name",
"petType"
],
"properties": {
"name": {
"type": "string"
},
"petType": {
"type": "string"
}
},
"subTypes": ["Cat"],
"discriminator": "petType",
"x-discriminator-value": "GenericPet"
}

Enumeration Extensions

We currently provide two extensions to let you enhance the models we generate from your enumerations. These are:

ExtensionTypeDescriptionApplicable to OpenAPI/Swagger Objects
x-enum-elementsEnum Element ObjectProvide additional meta-data for your enumerations by assigning a unique name for each element of your enum as well as specify a brief description for eachParameter Object, Items Object, Header Object, Schema Object (v2, v3)
x-enum-model-nameStringSpecify a custom name for the enumeration model to be generatedParameter Object when in isn't set to body. For other objects, use title for this purpose

Usage

The following example demonstrates the usage of both extensions in a Parameter Object:

{
"name": "numbers",
"in": "query",
"required": true,
"type": "string",
"enum": [
"1",
"2",
"3",
"4"
],
"x-enum-elements": [
{
"name": "One",
"description": "First element"
},
{
"name": "Two",
"description": "Second element"
},
{
"name": "Three",
"description": "Third element"
},
{
"name": "Four",
"description": "Fourth element"
}
],
"x-enum-model-name": "Number Elements"
}

Datetime Extensions

You can specify various date-time formats using our editor, the details of which are available at Datetime Formats. OpenAPI supports only one of these formats that is, Rfc3339. To let you make use of other datetime formats, we provide custom formats which you can specify through the format property at the time of defining a type. As per OAS (v2, v3), the format property is an open string-valued property, and can have any value to support documentation needs.

Taking advantage of the above, we make the following formats available to help you finely define the date-time type:

NameDescription
date-timeSupported by OpenAPI/Swagger by default. Represents datetime Rfc3339 format
date-time-rfc1123Helps represent datetime that uses Rfc1123 format
unix-timestampHelps represent datetime using Unix or Epoch time

Dynamic Response Extension

APIMatic supports type Dynamic for success responses where type schema isn't known or can't be easily defined. To use this type inside any version of Swagger, you can use our extension x-is-dynamic inside the response schema as follows:

{
"responses": {
"201": {
"description": "Successful operation",
"schema": {
"type": "object",
"x-is-dynamic": true
}
}
}
}

Exception Model Name Extension

We auto-generate exceptions models from the error response schema definitions to provide better support for handling API errors in generated code. By default, the models generated this way use the original schema's name/title and have a _Error postfix attached to them. You can, however, choose to override the auto-generated name with one of your own using our x-exception-model-name extension in OpenAPI's Schema Object (v2, v3).

NameTypeDescription
x-exception-model-nameStringWhen set, this name will override the default name assigned to an auto-generated exception model.

Example:

{
"paths": {
"/pets": {
"get": {
"operationId": "getPets",
.....................
"responses": {
"400": {
"description": "Unexpected error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/BadRequest"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"BadRequest": {
"x-exception-model-name": "ErrorResponse",
"type": "object",
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
}
}
}

In the above example, the exception model imported into APIMatic will be named ErrorResponse instead of BadRequest_Error.

Example Extensions

Swagger 2.0 doesn't have support for parameter level examples. If you need to specify examples for the Parameter Object, you can do so by using our extension described below:

ExtensionTypeDescription
x-exampleAnyExample value for the parameter
{
"name": "param1",
"in": "query",
"required": false,
"type": "string",
"x-example": "example value for param1"
}

API Metadata Extensions

The Info Object in OpenAPI (v2, v3) allows providing metadata about the API. We also offer some extensions that lets our users specify additional information about their API using this section.

ExtensionTypeDescription
x-image-uriStringAn absolute URL that points to a display image for the API

Example

  "info": {
"version": "1.1",
"title": "Swagger Petstore",
"x-image-uri": "http://example.com/image.png"
}

API Filtering Roles Extension

APIMatic supports role-based API filtering. If you choose to filter your API by roles, the resulting portal will only contain documentation for those endpoints available to the specific one or more roles. It works by matching endpoint-level tags with tags associated with specific roles. Information about the endpoint level tags comes from tags supported in OpenAPI at Operation level. However, to help specify information about available roles in the API, we support an extension called x-roles in the root OpenAPI object. See an example of it below:

Example Usage

info:
version: 1.0.0
title: Swagger Petstore
x-roles:
- name: private-role
id: "2"
tags:
- pets
description: private role

In below case, role with id 2 will have access to operations with tags containing "pet" but not those tagged as store.

  /pet:
post:
tags:
- "pet"
summary: "Add a new pet to the store"
...............
/store/inventory:
get:
tags:
- "store"
summary: "Returns pet inventories by status"
description: "Returns a map of status codes to quantities"
operationId: "getInventory"
.............

Details of the properties available within this extension are given below:

PropertyTypePurpose
nameStringName of the role.
idStringUnique identifier of the role.
descriptionStringProvides more details about the role.
tagsarray[String]List of String-valued tags associated with the role.

Applied Authentication Options Extension

You can extend the security information you apply globally or at operation level by adding additional metadata that can help provide more details about the security being applied. This metadata can be added using our extension x-security-options-meta which is applicable at the root OpenAPI/Swagger Object (v2, v3) and the Operation Object (v2, v3).

Details of the properties available within this extension are given below:

PropertyTypePurpose
nameStringA user-friendly name for the security option.
descriptionStringProvides more details about the security option.

Example Usage

 security:
- {}
- apiKey: []
x-security-options-meta:
- name: No Authentication
description: Authentication can be skipped. This will allow limited functionality, however.
- name: API Key
description: Pass the API key provided to you in your account settings. This will allow you full access to functionality.
danger

The number of items inside the extension must match the number of options in the security property else the extension data will be considered invalid or incomplete.

Response Mapping Object

Response Mapping Object is designed as a discriminated union with Type as the discriminator.

Currently, two types are supported:

Simple

Matches the current behavior i.e response from endpoint is treated as the result or error.

{
"Type": "Simple"
}

Field-Based

Data is extracted from a nested-field in the response's JSON object. Additionally, an error field can also be specified. Each element of the DataField or ErrorField corresponds to one level of nesting and implies the name of the field to be accessed for the data.

{
"Type": "FieldBased",
"DataField": ["nested", "data"],
"ErrorField": ["error"]
}

Error Templates

Error templates are custom-templated messages that can be provided for overriding default exception messages thrown in SDKs for error responses. They can be defined using a map like structure as shown below:

  "errorTemplates": {
"401": "Response returned an error with status code {$statusCode}.",
"402": "Error occurred: {$response.body#/errors/0/reason}",
"5XX": "Internal server error, Code: {$statusCode}.", //this error message will be thrown for all error responses with status codes belonging to the 5XX range.
"0": "An error occurred. Code: {$statusCode}" //this error message will be thrown for all error responses that are not covered explicitly in the error templates.
}

Here,

  • Key of an error template: Should be a valid HTTP error status code (400 - 599) or range (for example, 4XX, 5XX). The key can be set to 0 to represent any undeclared error codes.
  • Value of an error template: The exception message that the SDK must return in case of an error response belonging to the range specified in the template key. The error message defined here has support for templates that are replaced by real data at runtime. More details about the required syntax for the message can be found in the next section.

Error Template Message Syntax

The error template message is capable of supporting template expressions that hold placeholders which are replaced with actual data at runtime. A template expression must start and end with curly braces {}. The available placeholders that can be used are listed below:

PlaceholderDetails
$statusCodeThis is replaced by the actual response's status code at runtime for example, for an error response 401, the SDK exception message with a provided error template of Response returned an error with status code {$statusCode}. will become Response returned an error with status code 401.
$response.header.headerKeyThis is replaced with the content of the response header whose name's specified in place of the headerKey part of the placeholder for example, for a response with header X-Cache set to Hit, the SDK exception message with a provided error template like Could not fetch response data. Cache: {$response.header.X-Cache} will become Could not fetch response data. Cache: Hit.
$response.body#JsonPointerThis placeholder is replaced with the content of the response body. #JsonPointer is an optional segment of the placeholder to help retrieve a specific part of the JSON response body using JSON pointer syntax. If the value is non-primitive, it will be serialized first for example, for an error response with body {"error": {"reason": "Unauthorized"}}, the SDK exception message for provided error template like Response returned with error: {$response.body#error/reason} will become Response returned with error: Unauthorized.