SHARE THIS ARTICLE

Swagger CodeGen Extensions

OpenAPI/Swagger (v2.0, v3.0) facilitates third-party vendors to implement tool specific extensions. These extensions allow customizing behaviors beyond simple API descriptions. We at APIMATIC also offer extensions which are specific to Code Generation and can be specified within your Swagger API description 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 Swagger Extensions

Apparently when importing an API, the code generation settings appears to be non-customizable unless configured manually, after the import, through our UI editor. In case of Swagger, however, we provide extensions that you can use within your Swagger API to specify the said 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. CodeGen Settings
  2. Advanced Settings for Endpoints
  3. Additional Headers
  4. Basic Authentication Extensions
  5. OAuth 2.0 Extensions
  6. Discriminator Value Extension
  7. Enumeration Extensions
  8. Datetime Extensions
  9. Dynamic Response Extension
  10. Example Extensions

CodeGen Settings

APIMATIC offers numerous settings that enables you to configure generic code styling, endpoint settings, model settings, continuous integration settings, code branding options, etc at the time of generating code. More details of these can be viewed at Code Generation Settings.

In order to specify these settings you will need to use the CodeGen Settings extension. Using this extension simply involves using a property x-codegen-settings within the “Info” object. The “Info” object is used in Swagger for providing metadata about the API. Details of this object can be viewed at Swagger Info Object (v2, v3). The x-codegen-settings property is an object that will look something like this:

"info": {
    ...,
    "x-codegen-settings": {
        "nullify404": true,
        "generateAsyncCode": true,
        "useMethodPrefix": true,
        "useModelPostfix": true,
        "useControllerPostfix": true,
        "useEnumPostfix": true,
        "useConstructorsForConfig": true,
        "iOSUseAppInfoPlist": true,
        "iOSGenerateCoreData": false,
        "androidUseAppManifest": true,
        "collectParameters": false,
        "csharpDefaultNamespace": "ACME.CORP.API",
        "javaDefaultPackageName": "com.acme.corp.api",
        "appendContentHeaders": true,
        "brandLabel": "ACME Corp.",
        "userAgent": "APIMATIC 2.0",
        "enableAdditionalModelProperties": false
    }
}

These settings will be globally applicable to all operations and schema definitions. Details of the properties available within this extension are given below:

ParameterTypePurpose
generateAsyncCodeBooleanWhen true, the CodeGen engine generates asynchronous C# and Java code.
useMethodPrefixBooleanWhen true, HTTP verbs are used as prefix for generated controller methods.
useModelPostfixBooleanWhen true, a postfix “Model” is appended to all classes generated from schemas.
useControllerPrefixBooleanWhen true, a prefix “Controller” is appended to all controllers generated from path groups.
controllerPostfixStringThis helps specify custom postfix for controller names.
useEnumPostfixBooleanWhen true, a postfix “Enum” is appended to all enumerations lifted from “allowedValues”.
useConstructorsForConfigBooleanWhen true, configuration values e.g., authentication credentials, are accepted as controller constructor parameters. Otherwise, these values generate variables in a Configuration class.
iOSUseAppInfoPlistBooleanWhen true, configuration values e.g., authentication credentials, are expected in app-info.plist file for the iOS SDK. When set, this setting ignores useConstructorsForConfig flag.
iOSGenerateCoreDataBooleanWhen true, iOS CoreData schema and classes are generated.
androidUseAppManifestBooleanWhen true, configuration values e.g., authentication credentials, are expected in AndroidManifest.xml file for the Android SDK. When set, this setting ignores useConstructorsForConfig flag.
collectParametersBooleanWhen true, operation 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. When set, this is applied globally on all endpoints/operations. If you wish to use this option on specific endpoints, use the x-operation-settings::collectParameters instead.
csharpDefaultNamespaceStringA valid C# namespace value to be used as the default namespace. Leave empty or null to automatically generate.
javaDefaultPackageNameStringA valid Java package name to be used as the base package name. Leave empty or null to automatically generate. This value is applied for both Java and Android code generation templates.
enablePHPComposerVersionStringBooleanWhen true, adds version component to composer.json file in PHP SDKs. This can cause conflicts with Git tag-based version publishing and should be used with care.
phpComposerPackageNameStringThis will set the name in composer.json file for PHP SDKs. You must provide a string with the format your-vendor-name/package-name.
appendContentHeadersBooleanWhen true, code generation engine automatically detects request and response schema and appends content headers e.g., “accept: application/json” and “content-type: application/json” headers for JSON serialization mode.
brandLabelStringA string value to brand the generated files. For example: “Acme Corp.”
userAgentStringA string value to use as user-agent in the API calls. This is useful for analytics and tracking purposes. For example: “SDK V1.1”
enableAdditionalModelPropertiesBooleanWhen true, additional or unknown properties in the response JSON are collected into a dictionary.
nullify404BooleanWhen true, null response will be returned on the HTTP status code 404
useCommonSDKLibraryBooleanWhen true, a common library comprising of common classes is used by the generated SDKs
projectNameStringThe name of the project for the Generated SDKs
preserveParameterOrderBooleanWhen true, parameter order is tried to be preserved in endpoints and models
generateInterfacesBooleanWhen true, interfaces for controller classes are generated in the generated SDKs
validateRequiredParametersBooleanWhen true, required API endpoint parameters are validated to be not null
timeoutFloatWhen set, the requests will timeout after the specified duration
storeTimezoneInformationBooleanAttempts to preserves timezone information when any date-time type is parsed. Timezone is also included as part of serialized data when such data is sent. By default, this will be false and date-time types with timezone will be normalized to UTC.
enableLoggingBooleanEnabling this generates code in the SDKs for logging events in the API cycle using a libary.
applyCustomizationsarray[String]List of customer-specific customizations to apply.
sortResourcesBooleanWhen true, this sorts endpoint groups, endpoints and models during code generation (SDKs and docs)
allowSkippingSSLCertVerificationBooleanWhen true, it allow clients the option to make insecure endpoint calls that do not verify SSL certificate when using HTTPS
doNotSplitWordsarray[String]List of words that should not be split, regardless of the capitalisation. The order determines priority, from highest to lowest.
enableGlobalUserAgentBooleanEnable this to send the UserAgent field as the user-agent header or APIMATIC’s branding user-agent if the UserAgent field is empty. Disabling this will NOT disable user-agent from being sent if its set as a additional header or in endpoint parameters as a header param.
returnCompleteHttpResponseBooleanIf true, complete HTTP response including headers and status code will be returned
controllerNamespaceStringName of controller namespace in SDK.
arraySerializationStringArray serialisation for primitive types (applicable to form and query params) . Valid values are Indexed, UnIndexed, Plain, CSV, TSV, PSV
responseMappingResponse Mapping ObjectResponse mapping strategy to use for mapping the HTTP response to the result passed to the endpoint caller in an SDK.
generateModelsBooleanWhen true, model and enum classes will be generated in the SDKs.
generateExceptionsBooleanWhen true, exception classes will be generated in the SDKs.
throwForHttpErrorStatusCodesBooleanWhen true, SDKs will throw an exception on HTTP error status codes. Alternatively, the SDK will not throw an exception but instead pass the error status code to the caller gracefully.
usageExampleEndpointUsage Example Endpoint ObjectAllows the user to choose an endpoint for which to display a full usage example in the README.
isLatestVersionBooleanUsing this, user can specify whether this SDK is the latest version or not. Enabling this will hide version number from install commands and package repository links.
shortCopyrightNoticeStringUsing this, user can specify a copyright notice to prepend to all code files in an SDK. This setting will be ignored if the user is not allowed white-labelling.
licenseTextStringSpecify license text to use in place of the standard MIT License.

Advanced Settings

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

Two extensions are currently available which are defined below:

  1. Operation Settings
  2. Multiple Body Parameters Setting
  3. Deprecation Details

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"
            }
        }
    }
}

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 endpoints. For example Twitter Streaming API endpoints.
parameterCollectionNameStringRepresents the name of the model that represents CollectedParameters
methodNameStringWhen specified, it is used instead of the operation name (extracted from the operation ID/summary) for generating method names in SDKs. While an operation ID in Swagger 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.

Multiple Body Parameters Setting:

Since Swagger does not 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 Swagger file (generally inside #/definitions or #/components/schemas depending on the 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 e.g. 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"
    }
}

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"
            }
            ...
        ]
    }
}
"securitySchemes": {
    "basicAuth": {
        "type": "http",
        "scheme": "basic",
        "x-additional-headers": [
            {
                "name": "api-version",
                "description": "The version number indicator for the API",
                "schema": {
                    "default": "1.1"
                }                
            },
            {
                "name": "sdk-version",
                "description": "The version number indicator for the SDK",
                "schema": {
                    "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 e.g. name
x-rename-password-asStringThe alternate name for password parameter e.g. 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"
    }
}
"securitySchemes": {
    "basicAuth": {
        "type": "http",
        "scheme": "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.0 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"
    }
}
"securitySchemes": {
    "oauth2": {
        "type": "oauth2",
        "flows": {
            "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

*   The extension is not applicable to flow password if x-skip-client-authentication is set to true.

Discriminator Value Extension

Swagger makes use of a property discriminator to support polymorphism in custom types. As per Swagger, 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 Swagger 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 Swagger 3.0, 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"
}
"Pet": {
    "type": "object",
    "required": [
        "name",
        "petType"
    ],    
    "properties": {
        "name": {
            "type": "string"
        },
        "petType": {
            "type": "string"
        }
    },
    "discriminator": "petType",
    "x-discriminator-value": "GenericPet"
}
"Pet": {
    "title": "Pet",
    "required": [
        "name",
        "petType"
    ],
    "type": "object",
    "properties": {
        "name": {
            "type": "string"
        },
        "petType": {
            "type": "string"
        }
    },
    "discriminator": {
        "propertyName": "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 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 is not 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. Swagger supports only one of these formats i.e. 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 the Swagger spec (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 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 is not known or cannot 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
        }
      }
    }
}

Example Extensions

Swagger 2.0 does not 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"
}

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"]
}

Usage Example Endpoint Object

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

ParameterTypePurpose
EndpointNameStringName of the chosen endpoint.
EndpointGroupNameStringGroup name of the chosen endpoint.
DescriptionStringAn optional description to show along with the usage example.

Example

{
    "EndpointName": "Get Pet",
    "EndpointGroupName": "Pets"
}

Have questions? Submit a request.