mczachurski / swiftgger Goto Github PK
View Code? Open in Web Editor NEWOpenAPI support for server side Swift projects.
License: MIT License
OpenAPI support for server side Swift projects.
License: MIT License
Hello!
Right now some of our handlers return plain strings instead of JSON. For example,
private func getAppHealthHandler(_ req: Request) throws -> String {
"All good!"
}
So I would like to ask you to make it possible to show raw string under "Example Value".
Because it shows empty brackets at the moment. See attached image.
See the code snippet:
let openAPIBuilder = OpenAPIBuilder(
title: "Tasker server API",
version: "1.0.0",
description: "This is a sample server for task server application."
)
.add([
APIObject(object: "Text Response")
])
.add(APIController(name: "Test", description: "Controller where we can manage test", actions: [
APIAction(method: .get,
route: "/test",
summary: "Summary",
description: "Description",
responses: [
APIResponse(code: "200",
description: "Ok",
object: String.self,
contentType: "text/plain")
],
authorization: false)
])
)
let openAPIDocument = openAPIBuilder.built()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try! encoder.encode(openAPIDocument)
let jsonString = String(bytes: jsonData, encoding: .utf8)
print(jsonString!)
return jsonString!
Also we do not need 'String' in Models section.
Thanks you!
Hello!)
Friend, please tell me. Taskerswift-swagger is currently hosted at azurewebsites.net. - https://taskerswift-swagger.azurewebsites.net/
How can I host it on my server?
Example - https://taskerswift-swagger.my-server.net/
Is it possible?
Numbers are represented as String, in examples, due to quotes/doublequotes.
As the examples template e.g. POST, the quotes need to be removed for using "try".
Hello!
I am experiencing problems with incorrect values I used to demonstrate params for request body. See attached image.
And see the code snippet and json below:
struct TestObject {
var test: String
var authClientIds: [UUID]
}
`
let openAPIBuilder = OpenAPIBuilder(
title: "Tasker server API",
version: "1.0.0",
description: "This is a sample server for task server application."
)
.add([
APIObject(object: TestObject(test: "Test-ID", authClientIds: [UUID(), UUID()])),
])
.add(APIController(name: "Users", description: "Controller where we can manage users", actions: [
APIAction(method: .post,
route: "/users",
summary: "Test",
description: "Test",
request:
APIRequest(object: TestObject.self, description: "Test description"),
responses: [
APIResponse(code: "200",
description: "Ok",
object: TestObject.self)
],
authorization: false)
])
)
let openAPIDocument = openAPIBuilder.built()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try! encoder.encode(openAPIDocument)
let jsonString = String(bytes: jsonData, encoding: .utf8)
print(jsonString!)
return jsonString!
`
json.txt
What I am doing wrong?
I expect to get the following under Example Value:
{
"authClientIds": ["26E490CF-31C5-4A12-A212-74BF7A896CC6", "39E490CF-31C5-4A12-A212-74BF7A896CC6"]
"test": "test-str"
}
Could you please take a look at this issue?
Hi,
First off, wonderful package!
I'm trying to add my models to schemas for the swagger specs. We are using enum
s to encapsulate models and functionalities, therefore, my model names are not exactly clear when added as APIObject
.
For example this might be a model of mine:
enum Models {
enum Transactions {
enum Response {
final class List: Content {
....
}
}
}
}
now, as you can see, when I add a transaction list item, all I get in Schemas section is: List
which is not at all clear to user.
Is there something I'm missing?
My suggestion (Swift being crazy when it comes to reflection, and use-cases being very different), it might be a good idea to let developers choose the type's name when adding the APIObject
.
Thanks
This would help with storing it in a cache so that we don't need to generate it every time
Hi! I need help from Authorization header, please.
My APIParameter -
APIParameter(name: "Authorization", parameterLocation: .header, description: "Bearer xxxxxx", required: true, dataType: .string)
I do not understand whether I'm doing everything? But I can't get access using real Token
Thanks in advance!
Hello!
I think that it might be helpful for someone if you will add explanation for the following issue to 'readme' file:
Swiftgger >=1.4.0 contains incompatible tools version and root depends on Swiftgger >=1.5.0, version solving failed
This error happens when the main project uses the latest version of Swiftgger and swift version lower then 5.3 (5.2 for example)
Thanks
Hello!
Could you please to release separate version of Swiftgger built with swift 5.2?
We are using Vapor 4.0 and Docker. And the problem is we need to use swift 5.2 according the the following document:
https://docs.vapor.codes/4.0/deploy/docker/
Hello!
Could you please to take a look at the following issue:
I have found that a collection of encodable objects is missing under Example Values. See image below:
And here is a code snippet to reproduce the issue:
struct NestedObject: Encodable {
var version: String
var value: String
}
struct TestObject: Encodable {
var nested: NestedObject
var nestedObjects: [NestedObject]
var nestedValues: [String]
}
let nested1 = NestedObject(version: "1.0", value: "Nested Object 1")
let nested2 = NestedObject(version: "2.0", value: "Nested Object 2")
let nested3 = NestedObject(version: "3.0", value: "Nested Object 3")
let test = TestObject(nested:nested1, nestedObjects: [nested2, nested3],
nestedValues: ["Str1", "Str2"])
let openAPIBuilder = OpenAPIBuilder(
title: "Tasker server API",
version: "1.0.0",
description: "This is a sample server for task server application."
)
.add([
APIObject(object: test)
])
.add(APIController(name: "Test",
description: "Controller where we can manage test",
actions: [
APIAction(method: .get,
route: "/test",
summary: "Summary",
description: "Description",
responses: [
APIResponse(code: "200",
description: "Ok",
type: .object(TestObject.self))
],
authorization: false)
])
)
let openAPIDocument = openAPIBuilder.built()
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let jsonData = try! encoder.encode(openAPIDocument)
let jsonString = String(bytes: jsonData, encoding: .utf8)
print(jsonString!)
return jsonString!
Hello again!)
I hope this is my last question))
When I initialize the Struct and add it as APIObject (object: userResponse)
The description in the description of the circuit is all displayed perfectly!
But when I do the same with the class I get a completely different result.
It is - final class User
What am I doing wrong?
The library cannot be compiled with Swift 4.1 because of the error in OpenAPIExample.swift
, line 47:
try container.encode(value, forKey: .value) // ERROR: Reference to member 'value' cannot be resolved without a contextual type
That's because the value
property is of type Optional<Any>
. Prior to Swift 4.1 Optional
conformed to the Encodable
protocol unconditionally at compile time, but attempting to encode its payload if the payload is not itself Encodable
would crash at runtime.
Swift 4.1 introduced conditional conformances, and now this error is caught at compile time, which results in the inability to compile Swiftgger.
My suggestion would be to make the OpenAPIExample
class generic:
-public class OpenAPIExample: Encodable
+public class OpenAPIExample<Value: Encodable>: Encodable {
public private(set) var ref: String?
public private(set) var summary: String?
public private(set) var description: String?
- public private(set) var value: Any?
+ public private(set) var value: Value?
public private(set) var externalValue: String?
However, I haven't tried this and not sure if it'll work with the rest of the project.
I'm looking forward to be able to use Swiftgger in my Vapor project 😊
Nested objects are treated like simple strings when you generate OpenAPI definitions. Is it not supported or am I doing something wrong? I can't find any examples with the nested objects.
Hi,
For the api
http://localhost:8080/myapi/?offset=2&limit=10
On Package.swift
I declare:
.package(url: "https://github.com/mczachurski/Swiftgger.git", from: "1.2.2")
The peace of code for Swiftgger:
struct MyObject {
let id: Int
let name: String
}
var lActions:[APIAction] = []
let lMyApi = APIAction(
method: .get, route: "/myapi",
summary: "Some summary",
description: "some description",
parameters: [
APIParameter(name: "offset", parameterLocation: .query, description: "offset description", required: false),
APIParameter(name: "limit", parameterLocation: .query, description: "limit description", required: false)
],
responses: [
APIResponse(code: "200", description: "OK", array: MyObject.self, contentType: "json")
],
authorization: true)
lActions.append(lMyApi)
let lOpenAPI = OpenAPIBuilder(
title: "MyAPI",
version: "1.0.0",
description: "MyAPI description"
)
lOpenAPI.add(lAPIController)
.add([
APIObject(object: MyObject(id: 100, name: "name of the object"))
])
When I call http://localhost:8080/swagger.json
Swiftgger generate:
{
"paths": {
"/myapi": {
"get": {
"parameters": [
{
"deprecated": false,
"allowEmptyValue": false,
"in": "query",
"name": "offset",
"description": "offset description",
"required": false
},
{
"deprecated": false,
"allowEmptyValue": false,
"in": "query",
"name": "limit",
"description": "limit description",
"required": false
}
],
"tags": [
"MyApi"
],
"deprecated": false,
"responses": {
"200": {
"content": {
"json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/MyObject"
}
}
}
},
"description": "OK"
}
},
"description": "some description",
"summary": "Some summary"
}
}
},
"servers": [
],
"openapi": "3.0.1",
"info": {
"title": "MyAPI",
"version": "1.0.0",
"description": "MyAPI description"
},
"tags": [
{
"name": "MyApi",
"description": "Test APIs"
}
],
"components": {
"schemas": {
"MyObject": {
"type": "object",
"properties": {
"name": {
"type": "string",
"example": "name of the object"
},
"id": {
"type": "int",
"example": "100"
}
},
"required": [
"id",
"name"
]
}
},
"securitySchemes": {
}
}
}
To run Swagger UI locally I use Docker with this Dockerfile
:
FROM node
RUN npm update npm &&\
npm install http-server replace
RUN mkdir -p /tmp/swagger
ADD https://github.com/swagger-api/swagger-ui/archive/master.tar.gz /tmp/swagger/swaggerui.tar.gz
RUN tar --strip-components 1 -C /tmp/swagger -xzf /tmp/swagger/swaggerui.tar.gz
RUN mkdir -p /swaggerui/dist/swagger-ui &&\
mv /tmp/swagger/dist/* /swaggerui/dist/swagger-ui &&\
rm -rf /tmp/swagger
ENV API_URL http://petstore.swagger.io/v2/swagger.json
RUN echo "'use strict';\
var path = require('path');\
var createServer = require('http-server').createServer;\
var dist = path.join('swaggerui', 'dist');\
var replace = require('replace');\
replace({regex: 'http.*swagger.json', replacement : process.env.API_URL, paths: ['/swaggerui/dist/swagger-ui/index.html'], recursive:false, silent:true,});\
var swaggerUI = createServer({ root: dist, cors: true });\
swaggerUI.listen(8888);" > /swaggerui/index.js
EXPOSE 8888
And launch Swagger UI with the command line:
docker run --detach --rm --name swaggerui -p 8888:8888 -e "API_URL=http://localhost:8080/swagger.json" swaggerui:latest
On the browser I can see this:
And on the console I have this:
The parameters are not defined correctly but I do not see what needs to be done to correct this.
Objects with Decimal
attributes or nested Array (tested Array<Array<Array<Double>>>
) fail to serialize in the schema and fall back to another schema link.
[[[Double]]]
is typical for GeoJSON requests so it can't be split up into objects.
Decimal should be shown as a Number, not an object.
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.