SHARE THIS ARTICLE

Swagger CodeGen Extensions

Swagger 2.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 a similar extension 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 five CodeGen extensions which include the following:

  1. CodeGen Settings
  2. Advanced Settings
  3. Additional Headers
  4. OAuth 2.0 Extensions
  5. Discriminator Value Extension

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. The x-codegen-settings property is an object that will look something like this:

{
    "swagger": 2.0,
    "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.
useControllerPostfixBooleanWhen true, a postfix “Controller” is appended to all controllers generated from path groups.
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 true the requests will timeout after the specified duration

Advanced Settings

APIMATIC allows further customization of endpoints (called operations in Swagger) through the Advanced Settings extension. These settings can be specified inside an “operation” object Swagger Operation Object using property name x-operation-settings. See an example as following:

"paths": {
    "/pets": {
        "get": {
            ...,
            "x-operation-settings" : {
                "collectParameters" : false,
                "allowDynamicQueryParameters": true,
                "allowDynamicFormParameters": false,
                "isMultiContentStreaming": false
            }
        }
    }
}

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

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 a “Security Scheme” object Security Scheme Object 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"
            },
            ...
        ]
    }
}

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

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

OAuth 2.0 Extensions:

The 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 use our OAuth 2.0 extension x-skip-client-authentication inside the Security Scheme Object as follows:

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

Usage

The extension is used through the x-skip-client-authentication property.

PropertyTypePurpose
x-skip-client-authenticationBooleanWhen set to true, client app authentication using Client Id and Client Secret will be skipped

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

In case of Swagger 1.2, you can use this extension inside a Model Object as follows:

"Animal": {
  "id": "Animal",
  "required": [
    "id",
    "type"
  ],
  "properties": {
    "id": {
      "type": "long"
    },
    "type": {
      "type": "string"
    }
  },
  "subTypes": ["Cat"],
  "discriminator": "type"
  "x-discriminator-value":"GenericAnimal"
}

In case of Swagger 2.0, the extension can be used inside the Definitions Object as follows:

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

Have questions? Submit a request.