Configuration
November 30, 2022 · View on GitHub
CreateAPI supports a massive number of customization options to generate the most appropriate source code for your api.
To use these options, you must define a configuration file that includes these properties. This can be done using either YAML or JSON, for example:
.create-api.yaml:
access: internal
fileHeaderComment: |
// Generated by Create API
// https://github.com/CreateAPI/CreateAPI
entities:
defaultType: class
includeInitializer: false
paths:
style: operations
.create-api.json:
{
"access": "internal",
"fileHeaderComment": "// Generated by Create API\n// https://github.com/CreateAPI/CreateAPI\n",
"entities": {
"generateStructs": false,
"includeInitializer": false
},
"paths": {
"style": "operations"
}
}
After creating your configuration, you can use the --config option when running create-api to use it.
Below you can find the complete documentation for all available options.
Available Options
- generate
- module
- mergeSources
- vendor
- access
- annotateDeprecations
- useSwiftyPropertyNames
- inlineTypealiases
- acronyms
- indentation
- spaceWidth
- pluralizeProperties
- useNaiveDate
- fileHeaderComment
- commentOptions
- dataTypes
- package
- entities
- defaultType
- typeOverrides
- imports
- mutableProperties
- baseClass
- protocols
- includeIdentifiableConformance
- skipRedundantProtocols
- includeInitializer
- alwaysIncludeDecodableImplementation
- alwaysIncludeEncodableImplementation
- sortPropertiesAlphabetically
- optimizeCodingKeys
- includeDefaultValues
- inlineReferencedSchemas
- stripParentNameInNestedObjects
- exclude
- include
- nameTemplate
- filenameTemplate
- paths
- rename
generate
Type: Set
Default: [.entities, .paths, .enums, .package]
Different components that CreateAPI should generate.
Available options are .entities, .paths, .enums and .package.
Defaults to [entities, paths, enums, package].
module
Type: ModuleName
Default: ""
The name of the module that the generated sources will be part of.
You must specify a value for this option otherwise an error will be thrown when running the generator.
mergeSources
Type: Bool
Default: false
Merge generated Entities and Paths into single output files.
Merging the source files offers a compact output, but prevents the compiler from parallelizing build tasks resulting in slower builds for larger schemas.
vendor
Type: Vendor
Default: nil
Enable vendor-specific logic (supported values: github)
access
Type: Access
Default: .public
Access level modifier for all generated declarations
publicinternal
annotateDeprecations
Type: Bool
Default: true
Add @available(*, deprecated) attribute to deprecated types and properties
useSwiftyPropertyNames
Type: Bool
Default: true
Prefixes booleans with is ("enabled" -> "isEnabled")
inlineTypealiases
Type: Bool
Default: true
Any schema that can be converted to a type identifier.
For example, typealias Pets = [Pet] is inlined as [Pet].
acronyms
Type: [String]
Default: ["url", "id", "html", "ssl", "tls", "https", "http", "dns", "ftp", "api", "uuid", "json"]
A list of acronyms that should be uppercased when present in property names.
To disable uppercasing of acronyms, set this property to an empty array.
Examples
With the given schema:
type: object
properties:
user_id:
type: integer
image_url:
type: string
format: uri
acme_corporation:
type: boolean
No Acronyms
acronyms: []
var userId: Int
var imageUrl: URL
var isAcmeCorporation: Bool
Custom Acronyms
acronyms:
- id
- url
- acme
var userID: Int
var imageURL: URL
var isACMECorporation: Bool
indentation
Type: ConfigOptions.Indentation
Default: .spaces
Change the style of indentation. Supported values:
spacestabs
spaceWidth
Type: Int
Default: 4
Number of spaces to use when indentation is set to spaces.
pluralizeProperties
Type: Bool
Default: true
For example, public var file: [File] becomes public var files: [File]
useNaiveDate
Type: Bool
Default: true
Parses dates (e.g. "2021-09-29") using NaiveDate
fileHeaderComment
Type: String
Default: "// Generated by Create API\n// https://github.com/CreateAPI/CreateAPI"
Overrides file header comment
commentOptions
Type: Set
Default: [.title, .description, .example, .externalDocumentation, .capitalized]
Options used when generating comments.
Available options:
title- Include the schema title (if available)description- Include the schema description (if available)example- Include the schema example value (if available)externalDocumentation- Include a markdown formatted link to the schema's external documentation (if available)capitalized- Automatically capitalize the comments
To disable comments completely, set this property to an empty array.
Examples
Disable Comments
commentOptions: [] # or false
Description Only
commentOptions: description
Custom Comment
commentOptions: [description, capitalized]
Detailed Comment (default)
commentOptions:
- title
- description
- example
- externalDocumentation
- capitalized
dataTypes
Type: DataTypes
Default: DataTypes()
Change the data type format mapping to Swift types than what CreateAPI provides.
You can use this option in combination with entities.imports, paths.imports, and package.dependencies for mapping to types that the default library does not provide.
It is your responsibility to ensure that the replacement type conforms to Codable and can properly decode and encode to the original primative type.
Examples
Supporting custom formats:
dataTypes:
string:
uuid: String
phone-number: PhoneNumber # imported type
number:
float: Double
Disable fixed-width integer types:
dataTypes:
integer:
int32: Int
int64: Int
Disable usage of NaiveDate:
useNaiveDate: false # must be set otherwise `date` overrides are ignored
dataTypes:
string:
date: String
Entities
Options specifically related to generating entities
entities.defaultType
Type: EntityType
Default: .struct
The default type used when generating entities. Available options are struct, class or finalClass
To override the default value for individual entities, use the typeOverrides option.
Note: If this value is set to
structbut the entity cannot be represented as a struct (i.e when it contains a property that recursively contains itself), a warning will be logged and the type will generate asfinalClassinstead. You should explicitly handle this by using options such astypeOverridesorignoreinstead.
entities.typeOverrides
Type: [String: EntityType]
Default: [:]
A dictionary map that describes entities that should generate as a specific type that wasn't the defaultType
Examples
entities:
defaultType: struct
typeOverrides:
Animal: class
Dog: finalClass
entities:
defaultType: finalClass
typeOverrides:
Animal: class
entities.imports
Type: Set
Default: []
Modules to be imported within the source files for generated entities
entities.mutableProperties
Type: Set
Default: [.structs]
Generate properties as mutable based on the type they are contained within.
The default value is structs which means that structs will use mutable properties but classes won't.
Set this property to true (or [structs, classes]) to always generate mutable properties and false (or [] to never generate mutable properties).
Examples
Structs Only
entities:
mutableProperties: structs
struct Foo {
var bar: String
}
class Foo {
let bar: String
}
All Types
entities:
mutableProperties: true # or [classes, structs]
struct Foo {
var bar: String
}
class Foo1 {
var bar: String
}
entities.baseClass
Type: String
Default: nil
Base class used when generating class types
entities.protocols
Type: Set
Default: ["Codable"]
Protocols to be adopted by each generated entity
entities.includeIdentifiableConformance
Type: Bool
Default: false
Automatically generate Identifiable conformance for entities that include an id property.
entities.skipRedundantProtocols
Type: Bool
Default: true
Automatically removes Encodable or Decodable conformance when it is not required
entities.includeInitializer
Type: Bool
Default: true
Generate an initializer for each entity
entities.alwaysIncludeDecodableImplementation
Type: Bool
Default: true
Generate the init(from:) initializer for Decodable conformance, even when the compiler synthesized version could be used.
entities.alwaysIncludeEncodableImplementation
Type: Bool
Default: true
Generate the encode(to:) method for Encodable conformance, even when the compiler synthesized version could be used.
entities.sortPropertiesAlphabetically
Type: Bool
Default: false
Orders properties of an entity alphabetically instead of the order defined in the schema
entities.optimizeCodingKeys
Type: Bool
Default: true
When true (the default), uses a single StringCodingKey type allowing string literals to be used in the place of individual CodingKey enum types.
For schemas with a large number of entities, this approach significantly reduces the binary size of the compiled code (apple/swift#60287)
entities.includeDefaultValues
Type: Bool
Default: true
If set to true, uses the default value from the schema for the generated property for booleans
entities.inlineReferencedSchemas
Type: Bool
Default: true
Controls the behaviour when generating entities from nested allOf schemas.
Examples
With the following schema:
components:
schemas:
Animal:
properties:
numberOfLegs:
type: integer
Dog:
allOf:
- $ref: '#/components/schemas/Animal'
- type: object
properties:
goodBoy:
type: boolean
When this property is set to true (the default):
struct Animal: Codable {
var numberOfLegs: Int
}
struct Dog: Codable {
var numberOfLegs: Int
var isGoodBoy: Bool
}
However setting this property to false results results in the following:
struct Animal: Codable {
var numberOfLegs: Int
}
struct Dog: Codable {
var animal: Animal
var isGoodBoy: Bool
// ...
}
entities.stripParentNameInNestedObjects
Type: Bool
Default: false
Strips the parent name of enum cases within objects that are oneOf / allOf / anyOf of nested references
entities.exclude
Type: Set
Default: []
When set to a non-empty value, entities and entity properties with the given names will be ignored during generation.
Cannot be used in conjunction with include.
Examples
entities:
exclude:
- Pet
- Store.id
entities.include
Type: Set
Default: []
When set to a non-empty value, only entities matching the given names will be generated.
This cannot be used in conjunction with exclude.
entities.nameTemplate
Type: String
Default: "%0"
A template used when generating entity names to allow for prefixing or suffixing.
Examples
entities:
nameTemplate: "%0DTO" # PetDTO, StoreDTO, ErrorDTO
entities:
nameTemplate: "_%0" # _Pet, _Store, _Error
entities.filenameTemplate
Type: String
Default: "%0.swift"
Template to use for Entity file generation
Examples
entities:
filenameTemplate: "%0Model.swift"
Package
Options specifically related generated a Swift Package.
package.dependencies
Type: [PackageDeclaration]
Default: []
Additional remote Swift Package imports.
Examples
package:
dependencies:
- url: https://github.com/apple/swift-argument-parser
products:
- ArgumentParser
requirement:
exact:
version: 1.1.1
- url: https://github.com/apple/swift-algorithms
products:
- Algorithms
requirement:
range:
from: 1.0.0
to: 2.0.0
- url: https://github.com/apple/swift-metrics.git
products:
- Metrics
requirement:
closedRange:
from: 2.0.0
to: 2.9.1
- url: https://github.com/apple/swift-log
products:
- Logging
requirement:
branch:
name: main
- url: https://github.com/apple/swift-numerics
products:
- RealModule
- ComplexModule
requirement:
commit:
hash: 7f2d022d3d9b55bf812814f5d01896cbfa0fd4da
- url: https://github.com/apple/swift-system
products:
- SystemPackage
requirement:
from:
version: 1.2.1
Paths
Options specifically related to generating paths
paths.style
Type: ConfigOptions.PathsStyle
Default: .rest
The style used when generating path definitions
rest- Generates nest structs to represent path componentsoperations- Generates a plain list of request operations
Examples
Rest
// Uses namespaces and names based on the path for each request
Paths.pets.get(limit: nil) // GET /pets
Paths.pets.petID("1").get // GET /pets/1
Operations
// Uses the `operationId` defined in the schema for each request
Paths.listPets(limit: nil) // GET /pets
Paths.showPetById(petID: "1") // GET /pets/1
paths.namespace
Type: String
Default: "Paths"
The namespace type for all generated paths
paths.includeResponseHeaders
Type: Bool
Default: true
Generate response headers using HTTPHeaders
paths.imports
Type: Set
Default: ["Get"]
Modules to be imported within the source files for generated requests
paths.overriddenResponses
Type: [String: String]
Default: [:]
Allows you to override mapping of specific response types to a custom (or generated) type instead.
For example:
paths:
overriddenResponses:
MyApiResponseType: MyCustomDecodableType
paths.overriddenBodyTypes
Type: [String: String]
Default: [:]
Tell CreateAPI how to map an unknown request or response content types to a Swift type used in the path generation.
For example:
paths:
overriddenBodyTypes:
application/octocat-stream: String
paths.inlineSimpleRequests
Type: Bool
Default: true
Inline simple requests, like the ones with a single parameter
paths.inlineSimpleQueryParameters
Type: Bool
Default: true
Inline query parameters for simple requests instead of generating a Parameter type
paths.simpleQueryParametersThreshold
Type: Int
Default: 2
The threshold of query parameters to inline when using inlineSimpleQueryParameters.
paths.removeRedundantPaths
Type: Bool
Default: true
Remove redundant paths if possible
paths.exclude
Type: Set
Default: []
When set to a non-empty value, the given paths will be ignored during generation.
Cannot be used in conjunction with include.
paths.include
Type: Set
Default: []
When set to a non-empty value, only the given paths will be generated.
This cannot be used in conjunction with exclude.
paths.filenameTemplate
Type: String
Default: "%0.swift"
Template to use for Paths file generation.
Examples
paths:
filenameTemplate: "%0API.swift"
paths.useDataForMultipartFormDataRequestBody
Type: Bool
Default: true
If false, CreateAPI generates request body structures for "multipart/form-data" format just like it would for "application/json".
Otherwise the body of the generated Request will use Data. The default value is true.
When using Get and it's APIClient, because Multipart Form Data isn't supported from the Request body property, it is best to leave this option set to true.
If however you have implemented your API Client, and you prefer to use structured Codable types to encode a Multipart Form Data request body, setting this value to false can be more convenient.
You might also need to use the dataTypes option to customise the type used to represent binary data.
Rename
Options used to configure detailed renaming rules for all aspects of the generated code.
rename.properties
Type: [String: String]
Default: [:]
Rename schema properties prior to processing. Rules can apply to all properties or to properties of a specific entity.
Examples
rename:
properties:
favorite_food: food # renames any schema property called 'favorite_food` to food
User.first_name: name # renames only the 'first_name` schema property on the `User` entity
rename.parameters
Type: [String: String]
Default: [:]
Rename query parameters
rename.enumCases
Type: [String: String]
Default: [:]
Rename enum cases
rename.entities
Type: [String: String]
Default: [:]
Rename entities
rename.operations
Type: [String: String]
Default: [:]
Rename operations when using the "operations" style for path generation
rename.collectionElements
Type: [String: String]
Default: [:]
Rename anonymous collection elements. By default, use a singularized form of the property name
Note: Want to contribute to the documentation? Edit it here.