OpenAPI/Swagger 3.0 Parser and Swift code generator

Overview

SwagGen

Platforms SPM Git Version license

SwagGen is a library and command line tool for parsing and generating code for OpenAPI/Swagger 3.0 specs, completely written in Swift.

Swagger 2 support has been removed. For Swagger 2 use version 3.0.2 or the swagger_2 branch

Swagger parser

It contains a Swagger library that can be used in Swift to load and parse Swagger specs.

Swagger code generator

SwagGen is command line tool that generates code from a OpenAPI/Swagger 3.0 spec. Templates for any language can be written that leverage this generator.

It is an alternative the official swagger-codegen java code generator, and adds some improvements such as speed, configurability, simplicity, extensibility, and an improved templating language.

Swift template

SwagGen includes a bundled template for generating a client side Swift library for interfacing with the Swagger spec. It includes support for model inheritance, shared enums, discrete and mutable request objects, inline schemas, Codable and Equatable models, configurable options, generic networking stack, and many other niceties.

Installing

Make sure Xcode 11+ is installed first.

Mint

$ mint install yonaskolb/SwagGen

Homebrew

$ brew tap yonaskolb/SwagGen https://github.com/yonaskolb/SwagGen.git
$ brew install SwagGen

Make

$ git clone https://github.com/yonaskolb/SwagGen.git
$ cd SwagGen
$ make install

Swift Package Manager

Use as CLI

$ git clone https://github.com/yonaskolb/SwagGen.git
$ cd swaggen
$ swift run

Use as dependency

Add the following to your Package.swift file's dependencies:

.package(url: "https://github.com/yonaskolb/SwagGen.git", from: "4.4.0"),

And then import wherever needed:

import SwagGenKit
import Swagger

Usage

Use --help to see usage information

swaggen --help
Usage: swaggen <command> [options]

Commands:
  generate        Generates a template from a Swagger spec
  help            Prints this help information
  version         Prints the current version of this app

generate

swaggen generate path_to_spec

Use swaggen generate --help to see the list of generation options.

  • spec: This is the path to the Swagger spec and is a required parameter. It can either be a file path or a web url to a YAML or JSON file

  • --language: The language to generate a template for. This defaults to swift for now.

  • --template:: This is the path to the template config yaml file. It can either be a direct path to the file, or a path to the parent directory which will by default look for /template.yml. If this is not passed, the default template for the language will be used.

  • --destination: The directory that the generated files will be added to.

  • --option: An option that will be merged with the template config options with those in this argument taking precedence, meaning any existing options of the same name will be overwritten. This argument can be repeated to pass in multiple options. Options must specify the option name and option value separated by a colon, with any spaces contained in quotes. Nested options in dictionaries can be set by using a dot syntax. The following formats are allowed:

    • -- option myOption:myValue
    • -- option modelSuffix: Model
    • -- option propertyNames.identifier: id
    • -- option "myOption: my value"
  • --clean: Controls if and how the destination directory is cleaned of non generated files. Options are:

    • none: no files are removed (default)
    • all: all other files are removed
    • leave.files: all files and directories except those that start with . in the destination directory are removed. This is useful for keeping configuration files and directories such as .git around, while still making sure that items removed from the spec are removed from the generated API.
  • --verbose: Show more verbose output

  • --silent: Silences any standard output. Errors will still be shown

Example:

swaggen generate http://myapi.com/spec --template Templates/Swift  --destination generated --option name:MyAPI --option "customProperty: custom value --clean leave.files"

For the Swift template, a handy option is name, which changes the name of the generated framework from the default of API. This can be set in the template or by passing in --option name:MyCoolAPI.

Swift Template

List of all available options:

name action expected values default value
name name of the API String API
authors authors in podspec String Yonas Kolb
baseURL baseURL in APIClient String first scheme, host, and base path of spec
fixedWidthIntegers whether to use types like Int32 and Int64 Bool false
homepage homepage in podspec String https://github.com/yonaskolb/SwagGen
modelPrefix model by adding a prefix and model file name String null
modelSuffix model by adding a suffix and model file name String null
mutableModels whether model properties are mutable Bool true
modelType whether each model is a struct or class String class
modelInheritance whether models use inheritance. Must be false for structs Bool true
modelNames override model names [String: String] [:]
modelProtocol customize protocol name that all models conform to String APIModel
enumNames override enum names [String: String] [:]
enumUndecodableCase whether to add undecodable case to enums Bool false
propertyNames override property names [String: String] [:]
safeArrayDecoding filter out invalid items in array instead of throwing Bool false
safeOptionalDecoding set invalid optionals to nil instead of throwing Bool false
tagPrefix prefix for all tags String null
tagSuffix suffix for all tags String null
codableResponses constrains all responses to be Codable Bool false
anyType override Any with custom type String Any
numberType override default number type when format not specified String Double

If writing your own Swift template there are a few types that are generated that you will need to provide typealias's for:

  • ID: The UUID format. Usually UUID or String
  • File: The file format. Usually URL, Data or a custom type with a mimeType and fileName
  • DateTime: The date-time format. Usually Date
  • DateDay: The date format. Usually Date or a custom type.

Editing

$ git clone https://github.com/yonaskolb/SwagGen.git
$ cd SwagGen
$ swift package generate-xcodeproj

This use Swift Project Manager to create an xcodeproj file that you can open, edit and run in Xcode, which makes editing any code easier.

If you want to pass any required arguments when running in XCode, you can edit the scheme to include launch arguments.

Templates

Templates are made up of a template config file, a bunch of Stencil files, and other files that will be copied over during generation

Template config

This is the configuration and manifest file for the template in YAML or JSON format. It can contain:

  • formatter: Optional formatter to use. This affects what properties are available in the templates and how they are formatted e.g. Swift
  • templateFiles: a list of template files. These can each have their paths, contents and destination directories modified through Stencil tags. One template file can also output to multiple files if they path is changed depending on a list context. Each file contains:
    • path: relative path to the template config. The extension is usually .stencil or the type it is going to end up as
    • context: optional context within the spec. This is provided to the generated file, otherwise the full context will be passed. If this is a list then a file will be created for each object and the context within that list is used. (e.g. a file for every model in the spec definitions gets it's own definition context). Note that properties in the template options field can be used here
    • destination: optional destination path. This can contain stencil tags whose context is that from the context above. e.g. if context was definitions then the path could be Models/{{ type }}.swift and the filename would be the type of the definition. If this is left out the destination will be the same as the path, relative to the final destination directory. If it resolves to an empty string it will be skipped and not generated.
  • copiedFiles: this is an array of relative paths that will be copied to the destination. They can be files or directories. This is used for files that won't have their contents, filenames or paths changed.
  • options: these are the options passed into every stencil file and can be used to customize the template. These options are merged with the options argument, with the argument options taking precendance. These options can be references in template file paths and their contents.

An example template for Swift can be found here

Template Files

These files follow the Stencil file format outlined here https://stencil.fuller.li

Formatters

Formatters change what information is available to the templates and how it's formatted. They can be specified via the formatter property in the template config. Usually these would map to a specific target language, but can be customized for different purposes.

Output Languages

SwagGen can be used to generate code for any language. At the moment there is only a formatter and template for Swift

Swift API usage

Usage documentation can be found in the Readme that is generated with your template.


Attributions

This tool is powered by:

Thanks also to Logan Shire and his initial work on Swagger Parser

Contributions

Pull requests and issues are welcome

License

SwagGen is licensed under the MIT license. See LICENSE for more info.

Comments
  • Compile Errors in project

    Compile Errors in project

    I was using Swagger codegen until recently. I had encountered error. I tried to generate files from SwagGen. I downloaded the repo project and created xcodeproj using this command in terminal "swift package generate-xcodeproj". I opened the project but i had some compile time errors in Sources/SwagGenKit/Utilities.swift

    "/Users/next/Downloads/SwagGen-master/Sources/SwagGenKit/Utilities.swift:11:32: Same-type requirement makes generic parameter 'Key' non-generic"

    Did i do something wrong in the installation process? I created a script file in folder and tried to run the script file but i got "Swag: command not found". Please guide me

    opened by bharathreddy-97 22
  • [Bug] oneOf without encapsulated schema generates noncompilable code

    [Bug] oneOf without encapsulated schema generates noncompilable code

    Consider such structure:

      /path:
        get:
          summary: Some summary
          security:
            - APIAccess: []
          operationId: pathRequest
          parameters: []
          responses:
            '200':
              description: Some response
              content:
                  application/json:
                      schema:
                          oneOf:
                              - $ref: "#/components/schemas/Message"
                              - $ref: "#/components/schemas/Status"
    

    So, response with 200 code can be either Message or Status schema. Such structure results in this code:

    
    extension API {
        /** Some summary */
        public enum PathRequest {
        ...
            public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
                public typealias SuccessType = Status200
    
                /** Some response */
                case status200(Status200)
    
                public var success: Status200? {
                    switch self {
                    case .status200(let response): return response
                    }
                }
    ...
            }
        }
    }
    

    Which results in compile error Cannot find type 'Status200' in scope – that's true it was not defined.

    I solved this problem by encapsulating oneOf inside custom schema:

    schemas:
        Entity:
            oneOf:
                - $ref: "#/components/schemas/Message"
                - $ref: "#/components/schemas/Status"
    

    However, I spent some time figuring out how to overcome this bug. I expected framework to automatically generating such schema.

    opened by AlexRoar 13
  • Getting `Reference ... is unresolved` when generating from OAS3

    Getting `Reference ... is unresolved` when generating from OAS3

    Hi,

    I was wondering if OAS3 was supported and gave it a go.

    I used code from master, passed this spec as a launch argument. Getting Thread 1: Fatal error: Reference #/components/schemas/User is unresolved

    Not sure if it's a bug or something isn't supported yet.

    opened by Kastet 9
  • unknown argument: '--disable-sandbox' in homebrew

    unknown argument: '--disable-sandbox' in homebrew

    Hi there, I'm getting: :0: error: unknown argument: '--disable-sandbox' after running: brew tap yonaskolb/SwagGen https://github.com/yonaskolb/SwagGen.git brew install SwagGen

    This is due to the command: swift --disable-sandbox build -c release -Xswiftc -static-stdlib

    swift -version output: Apple Swift version 4.0.3 (swiftlang-900.0.74.1 clang-900.0.39.2) Target: x86_64-apple-macosx10.9

    xcode version 9.2

    Any idea why? Thank you!

    opened by matanelgabsi 9
  • [Question] Group API Endpoints by tags

    [Question] Group API Endpoints by tags

    Hi, first of all, thanks for your great work.

    I'm working on creating RxSwift + Moya Swift template for Swagger. It worked perfectly after some modifications in Swift3 Codegen. I can finally make a PR but it is painful with inconsistent Java coding conventions, complex codebase.

    Luckily, I found your awesome library while finalizing my code before making a PR (after nearly 2 months pending). I can easily understand your codes and implementing task #8. I will submit a PR after I finished.

    But I have a question: It is possible to groups API Endpoints by their tags then put them in one file for example: Fake.swift, Pet.swift, Store.swift, User.swift? I see your suggestion in #5 but couldn't find a solution for my case.

    opened by dangthaison91 9
  • Added anyType template option

    Added anyType template option

    Added anyType template option to be able to replace, for example Any or [String: Any] with AnyCodable and [String: AnyCodable].

    Did not find a way to do it using only template.

    opened by tapoton 8
  • Unused public struct Options

    Unused public struct Options

    I have generated the code for my Swagger... In the generated code there are struct Options are generated for header field

    that option are nowhere being set in the header anywhere.

    to initialise the request those value in option are required which is not being set in header field.

    Also i think those value should not be required in creating request

    My swagger yml is at http://relatr-dev.westeurope.cloudapp.azure.com:8080/swagger/

    You can refer the Signup request in which languageCode: and appVersion are required parameters for creating requesting but those are header parameters

    swift-template generation 
    opened by mihirpmehta 8
  • Make Swaggen library work on Linux and split Model/Request/Client

    Make Swaggen library work on Linux and split Model/Request/Client

    Sorry it's a big PR πŸ™‡β€β™‚οΈ

    This PR make swagger library work on Linux(with FoundationNetworking when needed) and still work on Darwin.

    I did these changes because I needed to have a generated library working on Linux and Alamofire even the version 5 don't support Linux(https://github.com/Alamofire/Alamofire/pull/3098).

    This PR will give more control on which part of generated code you want to use:

    • only Models (no need for Alamofire)
    • Models + Requests (no need for Alamofire / you can create a simple client if needed on Linux for example)
    • Models + Request + Client (required Alamofire)

    The generated code is usable with or without dynamic library(it will now work with dynamic dependencies in Xcodegen that are imported in multiples frameworks).

    This should change nothing at all to most people except the removal of Timeline(which is a class of Alamofire that have bleed into the client).

    This should simplify refactoring of any part of the template if needed. For example if we want to migrate out of Alamofire it easier because now there is only one part of the code to focus on to remove it.

    I did move code around lot and made multiple SPM targets but tried to reduce the other modifications to the strict minimum.

    β”œβ”€β”€ Client
    β”‚Β Β  β”œβ”€β”€ APIClient.swift
    β”‚Β Β  └── RequestBehaviour.swift
    β”œβ”€β”€ Models
    β”‚Β Β  β”œβ”€β”€ APIModel.swift
    β”‚Β Β  β”œβ”€β”€ AnyCodable.swift
    β”‚Β Β  β”œβ”€β”€ Coding.swift
    β”‚Β Β  β”œβ”€β”€ Enum.swift
    β”‚Β Β  └── Model.swift
    β”œβ”€β”€ Requests
    β”‚Β Β  β”œβ”€β”€ API.swift
    β”‚Β Β  β”œβ”€β”€ APIRequest.swift
    β”‚Β Β  β”œβ”€β”€ APIResponse.swift
    β”‚Β Β  β”œβ”€β”€ APIService.swift
    β”‚Β Β  β”œβ”€β”€ AnyRequest.swift
    β”‚Β Β  └── Request.swift
    └── SharedCode
        β”œβ”€β”€ APIClientError.swift
        └── APIResult.swift
    

    Issue

    • This force me to remove Timeline feature of Alamofire.

    Questions

    I'm not sure of what should be public in KeyedDecodingContainer if I can have guidance on that @yonaskolb ?

    opened by mackoj 7
  • Support `discriminator` property is on the model

    Support `discriminator` property is on the model

    OpenAPI 3 supports specifying the discriminator on either the model or response objects. Currently SwagGen only works when the discriminator is on the response. When it's on the model, inheritance doesn't work properly, all objects (for example, when parsing an array of objects), are of the base class, not the proper subclasses.

    https://swagger.io/docs/specification/data-models/inheritance-and-polymorphism/

    opened by chaseacton 7
  • Support for allOf

    Support for allOf

    Is there any support for allOf planned? The generated code for PushPaginated does not correctly inherit from the referenced types.

    Pagination:
          type: object
          properties:
            draw:
              type: integer
            recordsTotal:
              type: integer
              format: int64
            recordsFiltered:
              type: integer
              format: int64
            error:
              type: string
          required:
            - draw
            - recordsTotal
            - recordsFiltered
    PushItem:
          type: object
          properties:
            title:
              type: string
            subtitle:
              type: string
            content:
              type: string
    PushPaginated:
          type: object
          allOf:
            - $ref: '#/components/schemas/Pagination'
            - type: object
              properties:
                data:
                  type: array
                  items:
                    $ref: '#/components/schemas/PushItem'
    
    opened by kroegerama 7
  • Install version 3.0.2 via homebrew

    Install version 3.0.2 via homebrew

    Hello. I need support swagger version 2. I try install (macOS): brew tap yonaskolb/SwagGen https://github.com/yonaskolb/SwagGen.git/tree/swagger_2 brew install SwagGen But installed SwagGen 4.0.0: https://github.com/yonaskolb/SwagGen/archive/4.0.0.tar.gz

    How I can install SwagGen 3.0.2 version for support swagger 2?

    opened by StasanTelnov 7
  • Add support to optional Security Requirements and top-level inheritance

    Add support to optional Security Requirements and top-level inheritance

    • Adds support for optional security requirements fixing a crash.
    • Adds support for top-level security requirements inheritance and overriding.

    Top-Level:

    Screen Shot 2022-09-02 at 18 47 33

    Operation:

    Screen Shot 2022-09-02 at 18 21 40

    Crash

    When parsing a security requirement that included an empty array (optional marker), SwagGen was crashing.

    Screen Shot 2022-08-17 at 19 40 20

    Swagger/SecurityRequirement.swift:9: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    

    Screen Shot 2022-08-17 at 19 25 40

    opened by Lucien 0
  • SwagGen doesn't process the media type application/json;charset=UTF8

    SwagGen doesn't process the media type application/json;charset=UTF8

    We have an OpenAPI v3 JSON that has media types of application/json;charset=UTF8. These are ignored by SwagGen when processing request bodies as it's explicitly looking for application/json or variations thereof with *.

    I don't know how valid it is that this additional charset is being specified, the RFC for media types (https://datatracker.ietf.org/doc/html/rfc6838) talks about it in relation to text types only, but it's what we're working with in our automatically generated spec.

    opened by knellr 0
  • Issue with decoding when element is nullable array

    Issue with decoding when element is nullable array

    If you take the following array:

    [ {"id": 1, "name" : "test", "tags" : ["tag1", "tag2"]}, {"id":2, "name":"test2", "tags":null}]

    it fails on decode with the error: Expected to decode Array but found a null value instead.

    the "tags" element is correctly defined in the model as [String]? and the swagger document shows it is nullable.

    It its possible to get around this by using the SafeOptionalDecoding:true option, but I would not have expected that to be required.

    opened by AndyBond2007 0
  • The spec yaml files in this repo fail lots of Swagger validations

    The spec yaml files in this repo fail lots of Swagger validations

    Description

    If we pass /Specs/PetstoreTest/spec.yml through the online validator a https://editor.swagger.io, it throws these validation errors:

    image

    Same goes for /Specs/Rocket/spec.yml (there're tens of errors on this one, they wouldn't all fit in a single screenshot):

    image

    And /Specs/TBX/spec.json:

    image

    And /Specs/TestSpec/spec.yml:

    image

    And /Specs/TFL/spec.json:

    image

    Room for Improvement

    I think a great improvement would be to have a spec validation step in CI for this repo, so that on every PR we'd be checking if all the spec yaml files continue to be valid. Here's a reference: https://swagger.io/blog/api-design/validate-openapi-definitions-swagger-editor/

    opened by rogerluan 0
  • segmentation fault when attempting to generate from spec that contains `allOf` groups

    segmentation fault when attempting to generate from spec that contains `allOf` groups

    Hey πŸ‘‹

    I've recently spent some time fighting with SwagGen because it would enter a recursion when attempting to parse a given json spec.

    After much debugging, I narrowed down the problem to the presence of allOf groups in my spec.

    I read a few issues and PRs in this repo, did some shallow code review in key parts of the code base to try to understand what problem the presence allOf was causing, that was triggering the recursion. Some of the issues/PRs: #221, #286, #267, #269, #217, #278. I couldn't figure out why it's crashing (entering a recursion) on my specific spec file 😬 Specially because the sample specs present in this repo do feature allOf groups, so I don't know what specific configuration in my spec files is causing this particular problem 😞

    I tested with v4.3.1, v4.4.0, and v4.6.0, all of which caused the same problem (segmentation fault - a recursion somewhere).

    If it helps at all, here's the stack trace (click to expand):

    Line 0|Line 1|Line 2|Line 3|Line 4 --|--|--|--|-- ||||

    Workaround

    As a workaround for my specific case, since all of the allOf occurrences had a single element in the array, I replaced extracted its $ref out of the allOf key, directly in the JSON file, before parsing it using SwagGen. In Ruby, here's the script that worked for me:

    # Taken from https://stackoverflow.com/a/4174125/4075379
    def regex_replace_file(filename, regexp, replacement)
      require 'tempfile'
      Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
        File.open(filename).each do |line|
          tempfile.puts(line.gsub(regexp, replacement))
        end
        tempfile.close
        FileUtils.mv(tempfile.path, filename)
      end
    end
    
    swagger_spec_path = "/path/to/your/spec.json"
    regexp = /"allOf":\[\{("\$ref":"#\/components\/schemas\/[a-zA-Z]+")\}\]/m
    regex_replace_file(swagger_spec_path, regexp, '\1')
    
    # swagger_spec_path now contains the processed JSON file, ready to be consumed by SwagGen
    

    This workaround is admittedly terrible, but in my specific use case it didn't break anything. Use with caution.

    opened by rogerluan 5
  • "description" aka doc comments don't get generated nicely

    Hey πŸ‘‹

    I've found an issue where code like this:

    /**
    * This is a multiline
    * comment.
    */
    public myProperty: MyClass[];
    

    Gets translated into this swagger json:

    …
    "myProperty": {
        "description": "* This is a multiline\n\t *  comment.",
        "items": {
            "$ref": "#/components/schemas/MyClass"
        },
        "type": "array"
    },
    …
    

    Which SwagGen (understandably) generates this:

    // * This is a multiline
     * comment.
    public var myProperty: [MyClass]
    

    Although swagger could do a bit better with providing a better generated "description" (e.g. not including the * characters), I think SwagGen should at least provide code that compiles, e.g.:

    /// * This is a multiline
    /// * comment.
    public var myProperty: [MyClass]
    

    In other words: using the dedicated doc comment syntax (///) and adding that delimited to the start of the line so that it's recognized as a doc comment (which makes the code compile).

    Has this been considered? Or is there a better way to annotate doc comments in javascript? All the help is highly appreciated πŸ™ Thanks!

    opened by rogerluan 0
Releases(4.7.0)
  • 4.7.0(May 9, 2022)

    Changed

    • Expanded IntegerFormat to support more fixed width integers #301 @wqz-leo
    • Append more types of values to MultipartFormData including arrays and dictionaries #293 @0x0c

    Fixed

    • Fixed duplicated switch cases when using explicit mappings in oneOf discriminator #297 @JanC
    • Prefer generating composed types (oneOf, anyOf, ..) if the schema contains both type: object and oneOf #302 @JanC
    Source code(tar.gz)
    Source code(zip)
  • 4.6.0(Oct 4, 2021)

  • 4.5.0(Aug 5, 2021)

    Changed

    • Updated Alamore version in the Swift template to be 5.4.3 #273 @0x0c
    • Minimum Swift version in the Swift template is now 5.2 #273 @0x0c
    • Minimum iOS version in the Swift template is now 10 #273 @0x0c

    Fixed

    • Fixed sporadic crashes due to malformed URLs #268 @marcelvoss
    • Fixed generation of inline types for allOf #267 @nicholascross, #278 @liamnichols

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.4.0(Dec 28, 2020)

    Added

    • Support multiple authentication types per operation #222 @malteburkert
    • Added support for decimal number format #259 @yonaskolb
    • Added numberType, doubleType, floatType and decimalType template options #259 @yonaskolb
    • Added support for binary response bodies #224 @Hustenbonbon

    Fixed

    • Fixed inline allOf group generation
    • Fixed property generation when there is only one group schema; the first group schema type will be used as the type #217
    • Added anyType option that allows to override Any in models
    • Fixed date encoding formatter to conform to RFC3339
    • Fixed .swift-version to use Swift 5.2 instead of Swift 4.1 #246
    • Fixed Server is not defined issue #197

    Internal

    • SwagGen minimum Swift version is 5.0

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.3.1(Feb 1, 2020)

    Fixed

    • Fixed '??' has non-optional type warning #207
    • Fixed incorrect replacements in server variables #209
    • Fixed nullable references not being generated as optionals #216 @alephao

    Internal

    • Removed needless Array initialization. #212 @RomanPodymov

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.3.0(Nov 19, 2019)

    Added

    • Added ability to set nested template options from the command line using dot syntax eg --option "typeAliases.ID: String" #189
    • Added a customizable jsonEncoder on APIClient #172 #203
    • Added support for using a custom encoder per request #172 #203

    Changes

    • List operations by path and then by method to keep the order consistent between code generations #185
    • Add codableResponses option that constrains all models and responses to Codable #198
    • Add propertyNames option that allow to override the name of properties #196

    Fixed

    • Fixed responses from silently failing to parse when missing a description, which is now an optional property that defaults to an empty string #193
    • Add missing custom model protocol name #191
    • Fixed missing customization of JSONEncoder instance to encode request's body #147
    • Fixed string uploads #161

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.2.0(Jul 11, 2019)

    Swift Template Changes

    • Added support for objects in query params #158
    • Added support for nullable properties #165
    • Removed 3rd party Result framework #174
    • Fixed path to Enum.swift on Linux #157
    • Fixed model initializers with multiple levels of inheritance #175

    Fixes

    • Decode Swagger specs with no components #180

    Changes

    • Update dependencies

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.1.0(Mar 29, 2019)

    Added

    • Added swift template option enumUndecodableCase that adds an undecodable case to enums when decoding fails #141

    Fixed

    • Fixed installing in Swift 5 #139
    • Fixed Swift template building in Swift 5 by Alamofire #139

    Changed:

    • Updated codebase to Swift 5 and dropped Swift 4.2 #139

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 4.0.0(Mar 19, 2019)

    Added

    • Added support for OpenAPISpec/Swagger 3. Support for Swagger 2 has been removed. For that please use release 3.0.2 or the swagger_2 branch #118 #121
    • Added StencilSwiftKit support for templates #111
    • Added oneOf and anyOf with discriminators #121
    • Added support for generating inline schemas when they are wrapped in an array #121

    Swift Template Updates

    • Swagger 3 support #118
    • Added generated Server #118
    • Discriminated oneOf and anyOf enums #121
    • Allow both form and path parameters in the same request #118
    • Add headers to request #120
    • Add framework Info.plist #117
    • Use safeArrayDecoding #117
    • Catch APIClientError from RequestBehaviour validation #117
    • Added typeAliases option #117
    • Validation error changed from a String to an Error #117
    • Improve request description and summary #117
    • Change SecurityRequirement.scope string to SecurityRequirement.scopes array #117
    • Use StringCodingKey instead of enum types #117
    • Replace DateTime with Date #117
    • Update Alamofire dependency to 4.8.1 #123
    • Update Result dependency to 4.1.0 #123
    • Enums conform to Equatable and CaseIterable #124
    • Removed support for Swift 4.1 #124
    • Only generate isEqual in model classes not structs #117
    • Fixed path params that don't have swift friendly names #130
    • Fixed operations with mutiple success responses and no error responses #127
    • Fix nested schemas in subclasses thinking they have a parent #128
    • Handle nil modelProtocol option #117

    Removed

    • Removed support for Swagger 2 #118
    • Removed Swift 4.1 support #134

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 3.0.2(Feb 14, 2019)

    Added

    • Added example and default to the generator

    Fixed

    • Changed default date formatter in templates to use yyyy not YYY #114
    • Fixed date formatting of DateDay properties #114
    • Fixed encoding of dictionary types #113

    Internal

    • Updated to Swift 4.2
    • Updated YAMS, Rainbow and SwiftCLI

    Commits

    Source code(tar.gz)
    Source code(zip)
  • 3.0.1(Aug 25, 2018)

  • 3.0.0(Aug 24, 2018)

    Added

    • Added File upload support #103
    • Added top level security support #104
    • Added modelType option to Swift template for class or struct models #94
    • Added modelInheritance template option #94
    • Added modelNames and enumNames template options for overriding names #95
    • Added x-enum-name property to Swagger for custom enum names #98
    • Added operation summary to generation and template

    Changed

    • Swift template changes #104
      • Renamed APIError to APIClientError
      • Removed APIClient.authorizer
      • Added RequestBehavour.validate (replaces APIClient.authorizer)
      • APIClient.makeRequest now returns a CancellableRequest instead of Alamofire.Request
      • A new APIClient.jsonDecoder property which is used for json requests
      • Renamed queue to completionQueue in APIClient.makeRequest
      • Replaced APIError. authorizationError with APIClientError. validationError
      • Rename APIService.authorization to APIService.securityRequirement
    • Generated type changes in Swift template. You will now have to handle or typealias the following types #104
      • ID: The UUID format. Usually UUID or String
      • File: The file format. Usually URL, Data or a custom type with a mimeType and fileName

    Fixed

    • Sort operations in generated Readme
    • Better name camel casing #100
    • Fix empty string field decoding in YAML #101
    • Escape Protocol in swift templates
    Source code(tar.gz)
    Source code(zip)
  • 2.1.2(Jun 24, 2018)

    Added

    • Added generated Swift template documenation #87

    Fixed

    • Fixed nil AnyCodable values being encoded as null
    • Fixed inbuilt templates not being found in Mint installations
    Source code(tar.gz)
    Source code(zip)
  • 2.1.1(Jun 1, 2018)

    Added

    • Added support for ASCI encoded swagger specs #80

    Fixed

    • Fixed homebrew installation on machines with both Xcode 9.3 and Command line tools installed
    • Fixed UUID parameter encoding #81
    Source code(tar.gz)
    Source code(zip)
  • 2.1.0(May 17, 2018)

    Added

    • Separated date and date-time formats into DateDay and DateTime structs #74 #77
    • Added new modelPrefix and modelSuffix options #75

    Fixed

    • Fixed regression where request bodies were not being encoding properly #76
    • Fixed safeOptionalDecoding not working on optional Arrays
    • Fixed date-time not decoding in some cases #77
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(May 4, 2018)

    Added

    • Swift template: added Codable support to models #61
    • Swift template: added Equatable support to models #63
    • Swift template: added mutableModels option #64
    • Swift template: added safeArrayDecoding option #71
    • Swift template: added safeOptionalDecoding option #71
    • Bundle templates with installation #65
    • New language argument which defaults to swift for now #65
    • Default template for language is now used if no template path is specified #65
    • Added support for inline anonymous schemas in definitions, body params, and responses #66
    • Added UUID support #72
    • Added --silent flag #68
    • Added --verbose flag #68
    • Added --version flag #68

    Changes

    • Swift template: move sources out of now unnessary subdirectory #62
    • Swift template: reorganise template #69
    • Swift template: updated dependencies
    • Swift template: Update to Swift 4.1
    • Updated CLI #68
    • Improved error output #68
    • Make executable lowercase swaggen (breaking on linux) #68
    • BREAKING generation moved into generate command: swaggen generate #68
    • BREAKING --spec has changed to a required parameter: swaggen generate path_to_spec #68

    Removed

    • BREAKING Swift template: models no longer have init(jsonDictionary: JSONDictionary) or encode() -> JSONDictionary functions #61
    • Swift template: removed JSONUtilities dependency #61
    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Jan 11, 2018)

    Added

    • Added fixedWidthIntegers option to Swift template. Thanks @martinknabbe
    • Added support for response references #58

    Fixed

    • Fixed Swift 4.0.2 warnings
    • Fixed Brew install
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Sep 26, 2017)

    Added

    • Generate typealias for models with reference and array types #42 thanks @Liquidsoul
    • generate typealias for models that only have additional properties

    Fixed

    • fixed SPM installation issue
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Sep 25, 2017)

    Added

    • Swift template: decode response on background queue and then call completion on main thread or new queue parameter

    Changed

    • Updated project to Swift 4 #42
    • Updated Swift templates to Swift 4 #42
    Source code(tar.gz)
    Source code(zip)
  • 0.6.1(Aug 25, 2017)

    Added

    • Homebrew and Make installations
    • Enums now also have a raw property to access original json

    Changed

    • Requests in Swift template are final

    Fixed

    • Fixed parameters with a file type not being generated
    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(Jul 11, 2017)

    This includes a large rewrite with a lot more test cases so many more specs should be supported

    Added

    • Integer, Double and Float enums are now generated
    • operation now has hasFileParam and isFile #27 Thanks @dangthaison91
    • spec.operationsByTag now also includes operations without tags with an empty string name #28 Thanks @dangthaison91
    • Operations now include common parameters defined in the path #29 Thanks @dangthaison91
    • Added a bunch of test specs which are now validated against
    • Added a script that generates and then compiles all test specs

    Fixed

    • Removed symbols from generated filenames
    • Generate Floats as Float not Double
    • Fixed some array query parameters not joining their contents with the collectionFormat seperator (uses comma delimeted by default now if none is provided)
    • Arrays and dictionaries of enums are now encoded
    • Arrays of models are now encoded
    • Support for a default response with no schema
    • Support for [String: Any] responses
    • Simple type definitions including enums are generated properly
    • Fixed generation of operations without tags
    • Enums in responses are now generated
    • Overall more solid spec support. For example the whole fake petstore example now generates and compiles properly

    Changed

    • Within templates tags is now just a list of all tag names. The previous tag dictionary which contains name and operations has been moved to operationsByTag
    • request response enum cases have been renamed
    Source code(tar.gz)
    Source code(zip)
  • 0.5.3(May 22, 2017)

    Swift template fixes

    • fixed not building with Swift Package Manager in certain situations
    • fixed array bodies being generated as inline classes
    • fix compiler error when operations have no default response
    • escape built in Swift Foundation types like Error and Data
    • escape filenames in different way to class names

    Swift template changes

    • now uses Stencil includes. Paves the way for recursive nested schemas
    • changed how operations are decoded. Paves the way for non json responses
    • added APIError.name
    • made RequestAuthorizer.authorize completed parameter escaping
    • add tag to printed request and service descriptions

    Added

    Added suite of tests for parsing, generating and compiling templates from a list of specs. Will improve stability and help prevent regressions. Still some work to do in this area

    Source code(tar.gz)
    Source code(zip)
  • 0.5.2(May 16, 2017)

    Added

    • added SuccessType typealias to APIResponseValue. This lets you map from a response to successful value

    Changed

    • Replaced CustomDebugStringConvertible with PrettyPrinted conformance on Models, so you can specify your own CustomDebugStringConvertible. Same string is available at model.prettyPrinted
    • Moved generated request enums and anonymous schema from APIRequest.Request to one level higher in scope
    Source code(tar.gz)
    Source code(zip)
  • 0.5.1(May 16, 2017)

    Added

    • A request's response now has a responseResult with either .success(SuccessValue) or .failure(FailureValue). This is only generated if there is a single schema type for successes responses and a single schema type for failure responses

    Changed

    • Added back successType in response context for backwards compatibility with old templates
    • Updated Alamofire to 4.4.0

    Fixed

    • Fixed api name not being replaced in Decoding.swift anymore
    Source code(tar.gz)
    Source code(zip)
  • 0.5.0(May 15, 2017)

    Added

    • APIClient.makeRequest now returns an Alamofire Request if one was created, so requests can now be cancelled
    • All operation responses are now generated, not just the successful one, meaning you get access to typed errors

    Template Changes

    Model
    • Properties in a model subclass initialiser will now be ordered so that all required properties come first, instead of parent and then child's properties
    • Now provides a CustomDebugStringConvertible conformance that pretty prints all nested values
    APIRequest
    • Each APIRequest now has a typed Response enum that includes all it's responses in the spec. Each case has the decoded schema as an associated enum if specified
    APIClient

    The APIClient.makeRequest complete closure parameter has changed from DataResponse to APIResponse which:

    • replaces result value with the new response enum
    • has result error of APIError enum via antitypical/Result which has cases for:
      • unexpectedStatusCode(statusCode: Int, data: Data)
      • jsonDeserializationError(JSONUtilsError)
      • decodingError(DecodingError)
      • invalidBaseURL(String)
      • authorizationError(AuthorizationError)
      • networkError(Error)
      • unknownError(Error)
    Descriptions

    Models, Requests, Errors and Responses now have CustomStringConvertible and/or CustomDebugStringConvertible conformances

    Fixed

    • Path parameters are no longer also encoded as url parameters in the request template
    Source code(tar.gz)
    Source code(zip)
  • 0.4.1(May 11, 2017)

    Fixed

    Improved the generation of complicated specs:

    • escape all Swift keywords:
    • escape and rename invalid characters
    • escape symbols starting with numbers
    • better support for deeply nested arrays and dictionaries
    • fixed nested enums
    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(May 10, 2017)

    Added

    • Added generated API Client in Swift template #16
      • monitoring and modification of requests via request behaviours
      • asynchronous authorization of requests
      • central place for api options
      • configurable Alamofire SessionManager
    • Models now have support for additionalProperties #15
    • Swift template is now Swift Package Manager compatible #17
    • New clean CI arguement for ignoring dot files #18

    Changed

    • Names and properties in Swift template are now escaped with `` instead of appending Type,Enum ...etc

    Fixed

    • Swift names and types are now escaped with a greater range of swift keywords
    Source code(tar.gz)
    Source code(zip)
  • 0.3(May 4, 2017)

    Fixed

    • Operations with multiple path variables now properly generate an operationId. #11 Thanks @HSchultjan
    • Operation parameters that contain anonymous schemas (those that don't reference a definition schema but define a schema inline) are now genererated properly as nested structs within the APIRequest #13
    Source code(tar.gz)
    Source code(zip)
  • 0.2(May 3, 2017)

    Added

    • Operation, Definition, Property and Parameter, now have a raw property that can be accessed from templates. This represents the raw data that was in the original spec. This lets you access any custom properties you have in your spec

    Changed

    • Property and Parameter have lost their rawType and rawName properties in favour of the above, so they are now raw.type and raw.name
    • Upgraded Stencil to 0.9
    Source code(tar.gz)
    Source code(zip)
  • 0.1(May 3, 2017)

Owner
Yonas Kolb
iOS and Swift dev
Yonas Kolb
Delightful code generation for OpenAPI specs for Swift written in Swift

Create API Delightful code generation for OpenAPI specs for Swift written in Swi

Alexander Grebenyuk 286 Dec 23, 2022
The Swift code generator for your assets, storyboards, Localizable.strings, … β€” Get rid of all String-based APIs!

SwiftGen SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them ty

null 8.3k Dec 31, 2022
Gett's Design System code generator. Use Zeplin Styleguides as your R&D's Single Source of Truth.

Prism is a Design System code generator developed by the team at Gett ?? . Synchronizing design teams with engineering teams is a huge challenge. As t

Gett 346 Dec 31, 2022
Blazing⚑️Fast BTC and ETH Wallet Generator library for React Native, Android and iOS

Blazing ⚑️ Fast BTC and ETH Wallet Generator library for React Native, Android and iOS.

Coingrig 3 Feb 21, 2022
A dynamic sitemap generator for Vapor

A dynamic sitemap generator for Vapor

Vapor Community 5 Apr 21, 2022
XCSnippetsApp - macOS application to explore code snippets from the Swift and iOS community, view and edit the snippets before adding them conveniently to Xcode

XCSnippetsApp macOS application to explore code snippets from the Swift and iOS community, view and edit the snippets before adding them conveniently

Marco Eidinger 119 Dec 27, 2022
WebDomHandling - A Swift Package for handling JavaScript code between WebKit and Swift implemented by WebKit

WebDomHandling A Swift Package for handling JavaScript code between WebKit and S

null 0 Jan 23, 2022
A Swift SPM framework for running and managing Lua code from Swift

LuaKit A Swift Package for running and managing Lua code from Swift. Documentation For documentation, add this package as Swift Package Dependency, an

GGorAA 5 Nov 24, 2022
Command line tool for exporting resources and generating code from your Figma files

Fugen Fugen is a command line tool for exporting resources and generating code from your Figma files. Currently, Fugen supports the following entities

Almaz Ibragimov 69 Dec 17, 2022
A zero-code template app that demonstrates how to use TheraForge's APIs and can be used for fast prototyping

TheraForge MagicBox 1.0.0-beta The Open TheraForge (OTF) MagicBox app is a template for creating digital health solutions that help people better mana

TheraForge 0 Dec 23, 2021
Quizzler - iOS App Design Pattern(MVC) and Code Structuring

Quizzler iOS App Design Pattern(MVC) and Code Structuring What you will learn Ho

null 0 Jan 10, 2022
An Xcode Plugin to upload code snippets directly into Slack and Gist

XCSnippetr Share code snippets to Slack and Gist without leaving Xcode ever again! ?? Features Upload code snippets using Slack's and Github's APIs. T

Ignacio Romero Zurbuchen 100 Nov 29, 2022
You can monitor your APIs and websites on your menubar. Gives you status code πŸŽ‰ Cool & good

Hope not. Monitor your APIs and websites on your menubar. For macOS. Right now! YyeeeHav!

Steven J. Selcuk 10 Nov 29, 2022
SwiftTypeReader - You can gather type definitions from Swift source code.

SwiftTypeReader - You can gather type definitions from Swift source code.

omochimetaru 23 Dec 12, 2022
React Native library that implements PayPal Checkout flow using purely native code (swift).

react-native-paypal-swift React Native library that implements PayPal Checkout flow using purely native code (swift). Installation npm install react-n

Tibb 6 Nov 28, 2022
Some helpful swift code snippets

HelpfulSwiftSnippets Some helpful swift code snippets Network Manager - a generic network manager that deals with downloading data from the internet u

null 2 Oct 17, 2021
How to use swiftlint to identify unused code or unused imports in a Swift codebase

Swift compilation database This repository demonstrates how to use swiftlint to identify unused code or unused imports in a Swift codebase. How to run

AndrΓ©s Cecilia Luque 3 Aug 26, 2022
A simple Swift sample code to reads ISO 10303-21 exchange structure (STEP P21) file for AP242 schema.

simpleP21ReadSample A simple sample code to reads ISO 10303-21 exchange structure (STEP P21) file for AP242 schema. by Tsutomu Yoshida, Minokamo Japan

Tsutomu Yoshida 1 Nov 23, 2021
A template to solve Advent of Code problems using Swift

Advent Of Code Swift Template This repository serves as a template for an Xcode project set up to solve the Advent of Code problems in Swift. No attem

Christopher Luu 5 Dec 7, 2022