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.
- 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
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]
.
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.
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.
Type: Vendor
Default: nil
Enable vendor-specific logic (supported values: github
)
Type: Access
Default: .public
Access level modifier for all generated declarations
public
internal
Type: Bool
Default: true
Add @available(*, deprecated)
attribute to deprecated types and properties
Type: Bool
Default: true
Prefixes booleans with is
("enabled" -> "isEnabled")
Type: Bool
Default: true
Any schema that can be converted to a type identifier.
For example, typealias Pets = [Pet]
is inlined as [Pet]
.
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
Type: ConfigOptions.Indentation
Default: .spaces
Change the style of indentation. Supported values:
spaces
tabs
Type: Int
Default: 4
Number of spaces to use when indentation
is set to spaces
.
Type: Bool
Default: true
For example, public var file: [File]
becomes public var files: [File]
Type: Bool
Default: true
Parses dates (e.g. "2021-09-29"
) using NaiveDate
Type: String
Default: "// Generated by Create API\n// https://github.com/CreateAPI/CreateAPI"
Overrides file header comment
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
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
Options specifically related to generating entities
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
struct
but 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 asfinalClass
instead. You should explicitly handle this by using options such astypeOverrides
orignore
instead.
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
Type: Set
Default: []
Modules to be imported within the source files for generated entities
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
}
Type: String
Default: nil
Base class used when generating class
types
Type: Set
Default: ["Codable"]
Protocols to be adopted by each generated entity
Type: Bool
Default: false
Automatically generate Identifiable
conformance for entities that include an id
property.
Type: Bool
Default: true
Automatically removes Encodable
or Decodable
conformance when it is not required
Type: Bool
Default: true
Generate an initializer for each entity
Type: Bool
Default: true
Generate the init(from:)
initializer for Decodable
conformance, even when the compiler synthesized version could be used.
Type: Bool
Default: true
Generate the encode(to:)
method for Encodable
conformance, even when the compiler synthesized version could be used.
Type: Bool
Default: false
Orders properties of an entity alphabetically instead of the order defined in the schema
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)
Type: Bool
Default: true
If set to true
, uses the default
value from the schema for the generated property for booleans
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
// ...
}
Type: Bool
Default: false
Strips the parent name of enum cases within objects that are oneOf
/ allOf
/ anyOf
of nested references
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
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
.
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
Type: String
Default: "%0.swift"
Template to use for Entity file generation
Examples
entities:
filenameTemplate: "%0Model.swift"
Options specifically related generated a Swift Package.
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
Options specifically related to generating paths
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
Type: String
Default: "Paths"
The namespace type for all generated paths
Type: Bool
Default: true
Generate response headers using HTTPHeaders
Type: Set
Default: ["Get"]
Modules to be imported within the source files for generated requests
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
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
Type: Bool
Default: true
Inline simple requests, like the ones with a single parameter
Type: Bool
Default: true
Inline query parameters for simple requests instead of generating a Parameter type
Type: Int
Default: 2
The threshold of query parameters to inline when using inlineSimpleQueryParameters
.
Type: Bool
Default: true
Remove redundant paths if possible
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
.
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
.
Type: String
Default: "%0.swift"
Template to use for Paths file generation.
Examples
paths:
filenameTemplate: "%0API.swift"
Options used to configure detailed renaming rules for all aspects of the generated code.
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
Type: [String: String]
Default: [:]
Rename query parameters
Type: [String: String]
Default: [:]
Rename enum cases
Type: [String: String]
Default: [:]
Rename entities
Type: [String: String]
Default: [:]
Rename operations when using the "operations"
style for path generation
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.