yonaskolb / swaggen Goto Github PK
View Code? Open in Web Editor NEWOpenAPI/Swagger 3.0 Parser and Swift code generator
License: MIT License
OpenAPI/Swagger 3.0 Parser and Swift code generator
License: MIT License
When i try to generate the code for my swagger url, It generates a file called APIResult.Swift which looks like this
import Result
public typealias APIResult<T> = Result<T, APIError>
Compiler gives me error that
No such module 'Result'
If i replace import Result
with import Alamofire
the error changes to
Generic type 'Result' specialized with too many type parameters (got 2, but expected 1)
here is my URL from which i am generating the code
http://relatr-dev.westeurope.cloudapp.azure.com:8080/swagger/v1/swagger.json
This allows common responses to be defined at the top level and then referenced
Generate header parameters in Swift template
Needs support for additionalProperties (part of the OpenAPI specification). The official Swagger Codegen for Swift has some support for additionalProperties but would be great to see the same support in this project (as the code generated is so much nicer).
NB additionalProperties need to be supported in many cases:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject
I noticed that you didn't parse Path parameters in class Endpoint. Below is Instagram API I got from Swagger Editor.
Solution: Should we replace path: String
by path: Path
where Path
is a class/struct?
OTW, I was wonder why do you use class
instead of struct
. Maybe for creating other generators for other languages by inheritance?
YAML:
paths:
/users/{user-id}:
parameters:
- $ref: '#/parameters/user-id'
get:
security:
- key: []
- oauth:
- basic
tags:
- Users
description: Get basic information about a user.
/media/{media-id}:
parameters:
- name: media-id
in: path
description: The media ID
type: integer
required: true
get:
tags:
- Media
description: |
Get information about a media object.
The returned type key will allow you to differentiate between `image`
and `video` media.
At the moment the Swift compiler can complain if 2 files have the same filename, which can happen if a model name and operationId are the same, for example a model called Purchase.swift
and a request called Purchase.swift
I have the requirement to generate the type of a property without the optional mark (?).
Should I just update func getValueContext and extend it, i.e with
....
"optionalType": getValueType(value) + (value.required ? "" : "?"),
"type": getValueType(value),
Allows access to multiple response types.
Fixed by #20
I use stencils in Sourcery
and Swiftgen
and I miss some nice additions from StencilSwiftKit.
It would be really cool if SwagGen could use it. This would introduce some nice additions for custom templates like macro
, set
and some nice string filters
.
I saw that you use your own version of Stencil
to add some feature to the include
node. It may not be feasible but this is at least for your information in case you did not know it existed 😉
Hi yonaskolb,
You do a great job. But I met some build error when I build swagGen
My env is
Mac OS X EI Capitan 10.11.6
Xcode 8.0 (8A218a)
$ swift --version
Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-800.0.38)
Target: x86_64-apple-macosx10.9
The error log is:
$ swift build
Cloning https://github.com/kylef/PathKit.git
HEAD is now at 4597ab8 Release 0.7.0
Resolved version: 0.7.0
Cloning https://github.com/kylef/Spectre
HEAD is now at e46b75c chore: Release 0.7.2
Resolved version: 0.7.2
Cloning https://github.com/kylef/Commander.git
HEAD is now at 9304bbf chore: Release 0.6.0
Resolved version: 0.6.0
Cloning https://github.com/yonaskolb/Stencil.git
HEAD is now at ffd8804 added tests
Resolved version: 0.7.3
Cloning https://github.com/jpsim/Yams.git
HEAD is now at 71e81e9 release 0.2.0
Resolved version: 0.2.0
Cloning https://github.com/lucianomarisi/JSONUtilities.git
HEAD is now at a7aa1d6 Merge pull request #10 from lucianomarisi/chore/prepare-for-3.2.0-release
Resolved version: 3.2.0
Compile CYaml src/writer.c
Compile CYaml src/scanner.c
Compile CYaml src/reader.c
Compile CYaml src/parser.c
Compile CYaml src/loader.c
Compile CYaml src/emitter.c
Compile CYaml src/dumper.c
Compile CYaml src/api.c
Compile Swift Module 'JSONUtilities' (8 sources)
Compile Swift Module 'Spectre' (8 sources)
Linking CYaml
Compile Swift Module 'Yams' (9 sources)
Compile Swift Module 'PathKit' (1 sources)
Compile Swift Module 'Commander' (9 sources)
Compile Swift Module 'Stencil' (19 sources)
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:324:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
_ = value.withUnsafeMutableBytes { value in
^~~~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:346:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
_ = tag.withUnsafeMutableBytes { tag in
^~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:367:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes'
_ = tag.withUnsafeMutableBytes { tag in
^~~ ~~~~~~~~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Parser.swift:130:9: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeBytes'
utf8CString.withUnsafeBytes { bytes in
^~~~~~~~~~~ ~~~~~~~~~~~~~~~
/Users/secwit/Code/SwagGen/Packages/Stencil-0.7.3/Sources/Loader.swift:55:14: warning: no calls to throwing functions occur within 'try' expression
return try environment.templateClass.init(templateString: content, environment: environment, name: name)
^
/Users/secwit/Code/SwagGen/Packages/Stencil-0.7.3/Sources/Loader.swift:68:18: warning: no calls to throwing functions occur within 'try' expression
return try environment.templateClass.init(templateString: content, environment: environment, name: templateName)
^
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/secwit/Code/SwagGen/.build/debug.yaml
Reproducible failure when trying to install via Homebrew.
(install via git clone
, make
succeeded)
> brew install SwagGen
==> Installing SwagGen from yonaskolb/swaggen
==> Downloading https://github.com/yonaskolb/SwagGen/archive/2.1.0.tar.gz
Already downloaded: /Users/erwin/Library/Caches/Homebrew/SwagGen-2.1.0.tar.gz
==> make install PREFIX=/usr/local/Cellar/SwagGen/2.1.0
Last 15 lines from /Users/erwin/Library/Logs/Homebrew/SwagGen/01.make:
Cloning https://github.com/kylef/PathKit.git
Resolving https://github.com/kylef/PathKit.git at 0.8.0
Cloning https://github.com/onevcat/Rainbow.git
Resolving https://github.com/onevcat/Rainbow.git at 2.1.0
Cloning https://github.com/kylef/Spectre.git
Resolving https://github.com/kylef/Spectre.git at 0.7.2
Cloning https://github.com/jpsim/Yams.git
Resolving https://github.com/jpsim/Yams.git at 0.5.0
Cloning https://github.com/yonaskolb/JSONUtilities.git
Resolving https://github.com/yonaskolb/JSONUtilities.git at 3.3.8
Cloning https://github.com/jakeheis/SwiftCLI
Resolving https://github.com/jakeheis/SwiftCLI at 5.0.0
Cloning https://github.com/yonaskolb/Stencil.git
Resolving https://github.com/yonaskolb/Stencil.git at 0.9.3
make: *** [build] Error 1
If reporting this issue please do so to (not Homebrew/brew or Homebrew/core):
yonaskolb/swaggen
/usr/local/Homebrew/Library/Homebrew/utils/github.rb:220:in `raise_api_error': curl failed! (GitHub::Error)
curl: (22) The requested URL returned error: 422 Unprocessable Entity
curl: (3) <url> malformed
from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:178:in `open_api'
from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:292:in `search'
from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:225:in `search_issues'
from /usr/local/Homebrew/Library/Homebrew/utils/github.rb:238:in `issues_for_formula'
from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:368:in `fetch_issues'
from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:364:in `issues'
from /usr/local/Homebrew/Library/Homebrew/exceptions.rb:418:in `dump'
from /usr/local/Homebrew/Library/Homebrew/brew.rb:133:in `rescue in <main>'
from /usr/local/Homebrew/Library/Homebrew/brew.rb:25:in `<main>'
With the latest master source, I get an "Invalid Version" error message even though the code clearly checks for version 2 and my speck is "swagger": "2.0".
File: SwaggerSpec.swift line 84-88
version = String(describing: jsonDictionary["swagger"])
if let swaggerVersion = Double(version),
floor(swaggerVersion) != 2 {
throw SwaggerError.invalidVersion(version)
}
Seem that, current generator didn't return all model's properties as expected. When I user allProperties
it return parentProperties
only:
Expected:
context["allProperties"] = schema.properties.map(getPropertyContext) + schema.parentProperties.map(getPropertyContext)
Actual:
context["allProperties"] = schema.parentProperties.map(getPropertyContext)
Generate mocks for models and requests.
Can make use of swagger's example
field for this as well
Bundle the templates when installing and allow those templates as a default template for a language.
So instead of passing --template Templates/Swift/template.yml
you can pass --language swift
'switch' statement body must have at least one 'case' or 'default' block
ActivateCreate.swift
extension API.Auth {
....
public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible {
public typealias SuccessType = Void
public var success: Void? {
switch self {
}
}
The template options can provide some dictionaries to override model or request type names
Hey, I examined your project and realized that your project has no logo design yet. What do you think about it? If you interested I can contribute on your project with making logo design. Actually my main aims are supporting open source projects and make my portfolio better. I am waiting your feedback and if you have an idea we can talk about design decisions. Have a nice day! :)
Best Regards,
Baran Pirincal
Visual Communication Designer
I am trying to build SwagGen locally via command line (I have XCode8 installed).
Build is failing with following errors.
➜ SwagGen git:(master) swift build -c release Linking CYaml Compile Swift Module 'JSONUtilities' (8 sources) Compile Swift Module 'Spectre' (8 sources) Compile Swift Module 'Yams' (9 sources) /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:324:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = value.withUnsafeMutableBytes { value in ^~~~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:346:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = tag.withUnsafeMutableBytes { tag in ^~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Emitter.swift:367:13: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeMutableBytes' _ = tag.withUnsafeMutableBytes { tag in ^~~ ~~~~~~~~~~~~~~~~~~~~~~ /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/Packages/Yams-0.2.0/Sources/Yams/Parser.swift:130:9: error: value of type 'ContiguousArray<CChar>' (aka 'ContiguousArray<Int8>') has no member 'withUnsafeBytes' utf8CString.withUnsafeBytes { bytes in ^~~~~~~~~~~ ~~~~~~~~~~~~~~~ <unknown>:0: error: build had 1 command failures error: exit(1): /Users/sankalas/Downloads/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/sankalas/SwapnilSankla-backup/Delta/SwagGen/.build/release.yaml
The templates should be updated to support Swift 4 Codable Protocols as soon as Swift 4 is released.
Support inline Schemas within any Schema.
These would be generated as nested structs
Hi,
I have a problem with the generator, I get this error message: Fatal error: Reference #/responses/400 is unresolved: file /SwagGen/Sources/Swagger/Reference.swift, line 10
The problem is, that I have some references, which are numbers, so imagine the following:
'/application/{applicationId}/cob':
post:
summary: Lets a user to enter his country of birth
consumes:
- application/x-www-form-urlencoded
parameters:
- $ref: '#/parameters/applicationId_pathParam'
- name: cob
in: formData
description: Country of birth parameter in ISO 3166-1 alpha-2
type: string
required: true
responses:
'200':
description: 'Succesfully added country of birth param to {applicationId}'
'400':
$ref: '#/responses/400'
'500':
$ref: '#/responses/500'
The references are:
responses:
'400':
description: Validation error
schema:
type: array
items:
$ref: '#/definitions/BadRequestResponse'
'404':
description: Not found
'500':
description: Internal error
'501':
description: Not implemented yet
'503':
description: Service unavailable
This is not working. If I modify 400 to Code400 for instance, the generation is working as expected.
Ps: I also changed the responses
reference name to responseCode
reference name as I thought before that the problem is that the responses
name is special, but the problem persisted, so the problem is the numbers.
Thanks!!
Hey yonaskolb!
First off, really great project. I love SwagGen and the fact that I can now use a native app generating my models and requests plus using Stencil which I really love.
A quick question: Is it possible to specify only the routes or models which should be generated?
Similar to Swagger Codegens -Dmodels {opts}, -Dapis {opts}
flags?
That would be great!
Keep up the good work.
Kind regards
PS: Stencil has been updated and now allow % elif %. Would be great if you could update the dependencies. Perhaps even not constraining them to an exact version but e.g. specifying the major version ;-)
Once #32 is complete, it will remove the JSONUtilities dependency.
Is it worth removing the Alamofire dependency as well, which would make the generated code dependency free.
Would anyone miss the Alamofire integration? Is anyone hooking into it, or just using the plain ApiClient?
Support inline schemas in parameters which don't reference a definition.
For Swift these should be generated in the scope of the containing object. ie within the Request
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.
The swift template can have an option for simple responses. This would do away with each request decoding it's own error responses and make the completion handler of the APIClient
a simple Result of either success response or APIError
A custom URL class that completely overrides but does not inherit from the Swift URL class
making line 145 of the APICLient class
let url = URL(string: "\(baseURL)\(path)")!
not compile.
also the isEqual(to:) of the classModelAndView.swift
guard self.modelMap == object.modelMap else { return false }
has an error "Expression type 'Bool' is ambiguous without more context"
is it a setting I forgot?
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
template.yml
- path: request.swift
context: tags
If Swagger Spec doesn't define any tag, SwagGen couldn't generate API Endpoint with above configuration.
public var opererationsByTag: [String: [Operation]] {
var dictionary: [String: [Operation]] = [:]
for tag in tags {
dictionary[tag] = operations.filter { $0.tags.contains(tag) }
}
return dictionary
}
public var opererationsByTag: [String: [Operation]] {
var dictionary: [String: [Operation]] = [:]
if tags.isEmpty {
let defaultEndpointName = info.title.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
dictionary[defaultEndpointName] = operations
return dictionary
}
for tag in tags {
dictionary[tag] = operations.filter { $0.tags.contains(tag) }
}
return dictionary
}
Hi,
I found an other issue with the podspec, there's a dependency to an other library:
s.dependency 'JSONUtilities', '~> 3.3.8'
The error is: None of your spec sources contain a spec satisfying the dependency: 'JSONUtilities (~> 3.3.8)'.
I tried 3.2.0 and also without locking the version, so it would use 5.0.0 but both of them are breaking the generated code. This is the associated library: https://cocoapods.org/?q=jsonutilities
It seems they never had a version 3.3.8 :/
Hi, after the code is generated, where do I start using it?
There is no clear path to start using the API generated with your tool, could you possibly explain the generated architecture and logic of calls to the back end?
a sample would be greatly appreciated.
Regards.
Swagger provides the field format for integer types to distinguish between int32 and int64 (https://swagger.io/specification/#dataTypeFormat). This field is parsed in IntegerItem, though the SwiftFormatter ignores it and uses always Int as Swift type.
This can lead to loss of data, e.g. when Swagger specification contains int32 and generated code is running on device with 64-bit architecture. Putting a value bigger than int32 max into the field will result in a wrong value on receivers side.
Using a combination of method, path, and path params
Provide options in the Swift template for mutability of model properties
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!
Can we get some examples added to readme to kickstart using this? How to make an API request, specify parameters and return a User model perhaps?
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
Using
./SwagGen --template Templates/Swift --spec ~/Desktop/File.json
i'm obtaining the error
Error: The operation couldn’t be completed. (JSONUtilities.DecodingError error 0.)
What's wrong?
Use https://github.com/yonaskolb/Genesis for the template file and generation
Hi @Liquidsoul, I've noticed you've made some useful changes in your fork. Would you be open to submitting some of the general ones back into this repo via one or more PR's?
When generating code for https://api.closely.io/v1/location/swagger.json
the operationId is generated malformed for several requests.
PUT
request for the resource http://host/v1/location/{project}/devices/{device}"
Expected operationId:
putV1LocationByProjectByDevices
Actual operationId:
putV1LocationByProject}Devices{device
All caps Snakecase enum cases are not properly formatted. An enum with the value of PAYMENT_REQUEST
gets generated as:
case paymentrequest = "PAYMENT_REQUEST"
When it should be
case paymentRequest = "PAYMENT_REQUEST"
Any plan to support Swagger/OpenAPI 3.0 Spec
Update the swagger spec to 3.0 https://swagger.io/specification/
Maybe also rename the repo to make reference to OpenAPI? Any name suggestions?
The template should have an option to choose classes or structs.
If structs are used inheritance will have to be disabled
Hi,
Thanks for SwagGen
.
I would love to be able to add prefix or suffix to model filename and model class name.
I'm willing to implementing it. How can I do it ?
Thanks,
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.