apidevtools / swagger-parser Goto Github PK
View Code? Open in Web Editor NEWSwagger 2.0 and OpenAPI 3.0 parser/validator
Home Page: https://apitools.dev/swagger-parser
License: MIT License
Swagger 2.0 and OpenAPI 3.0 parser/validator
Home Page: https://apitools.dev/swagger-parser
License: MIT License
I am using such definition:
---
swagger: "2.0"
info:
version: "v0.1"
title: "Test"
description: ""
paths:
/test:
parameters: []
get:
responses:
200:
description: ""
schema:
type: "string"
examples:
application/json: "the devil’s place"
parameters: []
consumes:
- "application/json"
produces:
- "application/json"
operationId: "test"
summary: ""
description: ""
definitions: {}
basePath: "/mocks/a86239e0-d3af-48c6-9fd5-f8edc7c35d69"
host: "http://mocksvc.mulesoft.com"
schemes:
- "HTTP"
- "HTTPS"
produces:
- "application/json"
consumes:
- "application/json"
This is causing error because of the line "the devil’s place" which include a special character of apostrophe. Is it possible to support escaping it(and such other characters) internally instead of throwing error?
the above definition is validated as valid yaml here: http://www.yamllint.com/
As per the definition in https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields-13
we have swagger.json where we have defined schema example with "$ref": "../examples/example1.json" as given below.
But npm swagger-parser (3.3.0) .dereference() is throwing error like file not found, error resolving $ref.
Is there anything we defined against standards or issue with swagger-parser lib resolving $ref ?
swagger.json:
"responses": {
"200": {
"description": "Successful response",
"schema": {
"$ref": "./credit_card.json",
"example": {
"$ref": "../examples/example1.json"
}
}
}
},
Api tree:
API
|
|__examples/example1.json
|
|__schema/swagger.json
Error:
{
"name": "Error",
"message": "Error resolving $ref pointer "/temp/../../blah/blah/../../examples/example1.json".
"/temp/../../blahblah../../examples/example1.json" not found.",
"stack": "Error: Error resolving $ref pointer "/temp/../../blah/blah/../../examples/example1.json".
"/temp/../../blah/blah/../../examples/example1.json" not found.
at ono (/temp/../../../../../../swagger-parser/node_modules/ono/lib/index.js:67:20)
at $Refs._resolve (/temp/../../../../../../../node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/refs.js:150:11)
at /temp/../../../../../..//node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/dereference.js:49:29
at Array.forEach (native)
at crawl (/temp/../../../../../../../node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/dereference.js:40:22)
at /temp/../../../../../../../node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/dereference.js:61:22
at Array.forEach (native)
at crawl (/temp/../../../../../../../node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/dereference.js:40:22)
at /temp/../../../../../../../node_modules/swagger-parser/node_modules/json-schema-ref-parser/lib/dereference.js:71:22
at Array.forEach (native)"
}
swagger-parser has dependency on json-schema-ref-parser. But it allows any version of it. The latest version of json-schema-ref-parser (1.0.0-alpha.21) has broken $ref model.
Looks like the changelog hasn't been updated for the latest release. Just letting you know! 😎
I did 2 simple things
$ swagger bundle http://localhost/specification/src/v1/schema/swagger.json > ~/api_schema.json
$ swagger validate ~/api_schema.json
and got validation errors
while validating initial source said that it's valid
$ swagger validate http://localhost/specification/src/v1/schema/swagger.json
http://localhost/11/goalapi/specification/src/v1/schema/swagger.json is valid
I'm trying to deference swagger file for Google Drive service.
It's actually common problem for most of Google services.
I disable all options except for 'resolve$Refs' option.
I observing following output:
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
...
(node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.RangeError: Maximum call stack size exceeded
I ran the parser against the PetStore Spec and it was invalid. I got the following error message:
message: "Error in Swagger definition ↵SyntaxError: Array is too short (0), minimum 1 ↵Data path: "/paths/~1store~1inventory/get/parameters" ↵Schema path: "/properties/paths/patternProperties/^~1/properties/get/properties/parameters/minItems"↵"
Is this correct? I expected the example spec Swagger uses to be valid....
The following comes back as a valid spec according to swagger-parser. Note that the schema in the get
response does not include an items
attribute.
swagger: "2.0"
info:
version: "1.0.0"
title: Invalid API
paths:
/users:
get:
responses:
200:
description: hello world
schema:
type: array
PR below seems to resolve & includes a new test with the above scenario.
Hi there,
Great work on swagger-parser. I'm having an issue though: bundling pointers inside an externally reffed file seems to include the name of the pointer, where it shouldn't. I'm guessing the pointers are pretty much ignored.
Try parsing https://github.com/OAI/OpenAPI-Specification/tree/master/examples/v2.0/yaml/petstore-separate
from the OpenAPI specs (the entry point is spec/swagger.api
), and then validating it.
File spec/swagger.api
refers to parameters.yaml#/tagsParam
. Bundling will include the parameters.yaml
file and even select tagsParam
, but it also -- incorrectly -- includes the tagsParam
tag itself, rendering the resulting swagger.json invalid.
Let me know if I missed something here! Thanks for taking a look.
It would be handy to provide an option to "expand" a schema to resolve things like allOf
or oneOf
.
It seems like there has already been some work put into this for the JSON-Editor project.
https://github.com/jdorn/json-editor/blob/92857220697d0e4265a1945b9a469962c340921e/src/core.js#L417
I envision this being similar to the "dereference" option.
If there is interest in this, I'd be happy to contribute a pull request, I just need some guidance on the best way to include this. I was basically going to either clone or extend the "deference" option.
I have a master swagger.yaml, which looks like
...
definitions:
core.object:
$ref: "./definitions/core/object.yaml#/definitions/core.object"
...
My ./definitions/core/object.yaml
looks like:
swagger: "2.0"
definitions:
core.object:
type: object
properties:
id:
type: integer
type:
type: string
required:
- id
- type
discriminator: type
When bundle()
method produces the following output for me (does not resolve /definitions/core.object
part of the reference):
definitions:
core.object:
swagger: 2.0
definitions:
core.object:
type: object
properties:
id:
type: integer
type:
type: string
required:
- id
- type
discriminator: type
Interesting, but dereference()
produces correct output for me:
definitions:
core.object:
type: object
properties:
id:
type: integer
type:
type: string
required:
- id
- type
discriminator: type
I also tried require('json-schema-ref-parser').bundle(...)
and it also produces correct output. So looks like the issue is specifically with require('swagger-parser').bundle()
method...
Trying to parse/validate any yaml file results in the same error every time:
SyntaxError: Unable to resolve $ref pointer "file:///C:/Users/atom0s/Desktop/test/swagger.yaml"(…)
The file can contain anything in it, or be empty, no matter what I get this error. I'm attempting to parse on Windows 8.1.
The code I am testing with looks like this:
<script>
SwaggerParser.validate('swagger.yaml').then(function(api) {
console.log(api);
}).catch(function(err) {
console.error(err);
});
</script>
Given this folder structure:
| index.yaml
| parameters.yaml
| responses.yaml
|
+---definitions
| | index.yaml
| |
| +---error
| | error_model.yaml
| | extended_error_model.yaml
|
\---paths
| index.yaml
Consider this yaml:
index.yaml
swagger: '2.0'
info:
version: 1.0.0
title: User API
description: User specific API
schemes:
- http
- https
produces:
- application/json
- text/json
paths:
$ref: ./paths/index.yaml
definitions:
$ref: ./definitions/index.yaml
parameters:
$ref: ./parameters.yaml
responses:
$ref: ./responses.yaml
responses.yaml
# Common responses
200:
description: OK
schema:
type: string
DefaultError:
description: Error payload
schema:
$ref: '#/definitions/ExtendedErrorModel'
extended_error_model.yaml
allOf:
- $ref: '#/definitions/ErrorModel'
- type: object
properties:
detail:
type: string
meta:
type: string
error_model.yaml
type: object
required:
- status
- code
- title
properties:
code:
type: integer
title:
type: string
status:
type: integer
minimum: 100
maximum: 600
SwaggerParser.validate('index.yaml')
fails because '#/definitions/ExtendedErrorModel'
doesn't exist inside responses.yaml. However, if I use json-refs and js-yaml to load and parse the YAML, the resolution works.
I believe this is because json-refs first resolves all remote refs, then proceeds with local ones.
I'm not sure if the spec (OAI or json ref) dictates one way or the other. So I'm not sure if this is an issue or not.
Could you please shed some light on this?
When there is a Slash in a definition name ex Product/Part
the corresponding reference is : $ref=#/definitions/Offer~1Pricing
.
It appears that swagger-parser does not handle the slash escaping in references.
The following file fails to validate (it works when using http://editor.swagger.io/ ):
swagger: '2.0'
info:
title: "MWE"
version: "1.0.0"
host: localhost:8008
schemes:
- https
basePath: /path
paths:
"/thumbnail":
get:
summary: "Download a thumbnail"
produces: ["image/jpeg", "image/png"]
responses:
200:
description: "A thumbnail of the requested content."
headers:
Content-Type:
description: "The content type of the thumbnail."
x-example: "image/jpeg"
type: "string"
enum: ["image/jpeg", "image/png"]
schema:
type: file
{ [SyntaxError: Swagger schema validation failed.
Data does not match any schemas from 'oneOf' at #/paths/~1thumbnail/get/responses/200
Additional properties not allowed: x-example at #/paths/~1thumbnail/get/responses/200/headers/Content-Type
Additional properties not allowed: schema,headers,description at #/paths/~1thumbnail/get/responses/200
JSON_OBJECT_VALIDATION_FAILED] toJSON: [Function: errorToJSON] }
This uses a custom key x-example
on the Header Object
. This is valid swagger as per https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#headerObject
Removal of x-example
makes the parser validate successfully.
swagger-parser version: 3.2.1
I believe v2.5 resolved everything from the swagger.yml
source directory or process.cwd()
, but that appears to have changed after v3.
Is this configurable in v3?
To clarify, would prefer all references relative to a common base path, e.g. /fruits/orange.yml
would use:
$ref: /fruits/apple.yml
$ref: /vegetables/carrot.yml
rather than:
$ref: ./apple.yml
$ref: ../vegetables/carrot.yml
It would be awesome to have basic auth for http and/or pass cookies to the http request
Schema objects are allowed to have a discriminator property, which is described as
The discriminator is the schema property name that is used to differentiate between other schema that inherit this schema. The property name used MUST be defined at this schema and it MUST be in the
required
property list. When used, the value MUST be the name of this schema or any schema that inherits it.
The bolded sentence seems like something this parser should check. That is, these should fail (assume valid rest of swagger file):
# petType is not required
definitions:
Pet:
type: object
discriminator: petType
properties:
name:
type: string
petType:
type: string
required:
- name
# petType is not in properties
definitions:
Pet:
type: object
discriminator: petType
properties:
name:
type: string
required:
- name
Hi, I've this Swagger file. Please take a look to the dateOfBirth example fields, both are '1978-06-21'.
But after executing swagger-parser, output is an object and I don't know how obtain original value.
Could you please help me with this?
Thanks.
Swagger file:
info:
version: 0.0.1
title: Simple API
paths:
/persons:
get:
responses:
'200':
description: A list of Person
schema:
$ref: '#/definitions/Persons'
definitions:
Person:
title: Human
properties:
dateOfBirth:
type: string
format: date
example: 1978-06-21
lastTimeOnline:
type: string
format: date-time
readOnly: true
example: 2016-06-10T12:36:58.014Z
Persons:
properties:
items:
type: array
items:
$ref: '#/definitions/Person'
example:
- dateOfBirth: 1970-01-28
lastTimeOnline: 2016-04-10T14:36:58.014Z
Parser output:
"definitions": {
"Person": {
"properties": {
"dateOfBirth": {
"example": "1978-06-21T00:00:00.000Z",
"format": "date",
"type": "string"
},
"lastTimeOnline": {
"example": "2016-06-10T12:36:58.014Z",
"format": "date-time",
"readOnly": true,
"type": "string"
}
},
"title": "Human"
},
"Persons": {
"properties": {
"items": {
"example": [
{
"dateOfBirth": "1970-01-28T00:00:00.000Z",
"lastTimeOnline": "2016-04-10T14:36:58.014Z"
}
],
"items": {
"$ref": "#/definitions/Person"
},
"type": "array"
}
}
}
},
"info": {
"title": "Simple API",
"version": "0.0.1"
},
"paths": {
"/persons": {
"get": {
"responses": {
"200": {
"description": "A list of Person",
"schema": {
"$ref": "#/definitions/Persons"
}
}
}
}
}
},
"swagger": "2.0"
}
When the fetched URL exposes the CORS header 'Access-Control-Allow-Origin': '*'
, the request fails. I investigate and the problem is in json-schema-ref-parser
.
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
Webpack is using this lib as a http module https://github.com/substack/http-browserify
. And for some reason, the lib set by default xhr.withCredentials
to true
.
Adding withCredentials: false
on params given to http module solves the issue https://github.com/BigstickCarpet/json-schema-ref-parser/blob/v1.4.1/lib/read.js#L176
var req = protocol.get(
{
hostname: u.hostname,
port: u.port,
path: u.path,
auth: u.auth,
withCredentials: false,
},
onResponse
);
In this example, we use x-nullable
as a vendor extension to represent when a field is allowed to have an expressly null
value. As it stands now, we have to make address.yaml
contain this property for all uses (which is bad, because it's not always nullable).
# item.yaml
shipping_address:
x-nullable: true # I will be killed by the following $ref
$ref: "address.yaml"
# address.yaml
description: A generic address
properties:
# fields here
Once this is deferenced, x-nullable
has disappeared. It seems like this should be a merge, to allow for overrides as well.
# item.yaml
shipping_address:
description: A generic address
properties:
# fields here
When using generic/common objects, it's nice to provide usage-specific descriptions. Today we have to use one description for all uses, as the description will be stripped by dereferencing.
# item.yaml
shipping_address:
description: Shipping address for the item # I will disappear after $ref resolves
$ref: "address.yaml"
After dereferencing, this will strip off the overriden description:
# item.yaml
shipping_address:
description: A generic address
properties:
# fields here
When using this lib served on localhost, the lib doesn't fetch swagger urls with the right port and protocol. I investigate and the problem is in json-schema-ref-parser
.
Some params aren't passed to http
module which makes http
lib resolve url to fetch according to current protocol and port.
Replacing this block at https://github.com/BigstickCarpet/json-schema-ref-parser/blob/v1.4.1/lib/read.js#L176
var req = protocol.get(
{
hostname: u.hostname,
port: u.port,
path: u.path,
auth: u.auth
},
onResponse
);
by the following, solve the issue:
var req = protocol.get(
{
protocol: u.protocol,
host: u.host,
hostname: u.hostname,
port: u.port,
path: u.path,
auth: u.auth
},
onResponse
);
When I bundle my swagger files using swagger-cli, it works great but AWS API Gateway doesn't like the internal references, apparently.
This is the error I am getting:
No integration defined for method
It works fine for the first reference since presumably it is dereferenced. Do you have any thoughts on this? Could the swagger-cli allow all references to be dereferenced?
On all (of my) machines, the following snippet generates an max call stack size exceeded error. This only occurs in 3.4; I am using 3.3 without issue.
var spec = require('./json.json'); //slightly invalid swagger spec
var parse = require('swagger-parser');
parse.validate(spec, function(err, api){
if(err) console.log(err);
})
Full text of the error:
/private/tmp/sanity_check/node_modules/swagger-parser/node_modules/ono/lib/index.js:0
(function (exports, require, module, __filename, __dirname) { /**!
RangeError: Maximum call stack size exceeded
at Object.errorToJSON (/private/tmp/sanity_check/node_modules/swagger-parser/node_modules/ono/lib/index.js:141:21)
at formatValue (util.js:205:21)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
at formatValue (util.js:207:13)
Any idea what might be causing this?
I'm using dereference and calling JSON.stringify
with the output (api), and I get the following error:
D:\Programming\Projects\x\temprepo\gulpfile.js:10
fs.writeFileSync("swagger.json", JSON.stringify(api, null, 4));
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at D:\Programming\Projects\x\temprepo\gulpfile.js:10:51
at Immediate.invokeCallback [as _onImmediate] (D:\Programming\Projects\x\temprepo\node_modules\swagger-parser\node_modules\json-schema-ref-parser\lib\util.js:41:14)
at processImmediate [as _immediateCallback] (timers.js:367:17)
The file looks something like this:
NewsArticle:
title: NewsArticle
type: object
properties:
id:
type: integer
format: int32
x-mysql-type: int(11)
NewsArticleExt: # tmp
title: NewsArticleExt
type: object
allOf:
- $ref: "#/NewsArticle"
- properties:
test:
type: string
Is it possible to resolve the local pointer by copying the content instead of referencing it? Or is there some other way of making this work?
Hello,
I'm using swagger-parser@beta. When I try to use SwaggerParser in my React application I got this error :
ERROR in ./~/swagger-schema-official/schema.json
Module parse failed: /home/***/node_modules/swagger-schema-official/schema.json Unexpected token (2:9)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:9)
at Parser.pp$4.raise (/home/***/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/home/***/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp.semicolon (/home/***/node_modules/acorn/dist/acorn.js:581:61)
at Parser.pp$1.parseExpressionStatement (/home/***/node_modules/acorn/dist/acorn.js:966:10)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:730:24)
at Parser.pp$1.parseBlock (/home/***/node_modules/acorn/dist/acorn.js:981:25)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:709:33)
at Parser.pp$1.parseTopLevel (/home/***/node_modules/acorn/dist/acorn.js:638:25)
at Parser.parse (/home/***/node_modules/acorn/dist/acorn.js:516:17)
at Object.parse (/home/***/node_modules/acorn/dist/acorn.js:3098:39)
@ ./~/swagger-parser/lib/validate-schema.js 6:20-61
ERROR in ./~/json-schema-ref-parser/lib/resolvers/file.js
Module not found: Error: Cannot resolve module 'fs' in /home/***/node_modules/json-schema-ref-parser/lib/resolvers
@ ./~/json-schema-ref-parser/lib/resolvers/file.js 2:14-27
ERROR in ./~/z-schema/src/schemas/schema.json
Module parse failed: /home/***/node_modules/z-schema/src/schemas/schema.json Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:8)
at Parser.pp$4.raise (/home/***/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/home/***/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp.semicolon (/home/***/node_modules/acorn/dist/acorn.js:581:61)
at Parser.pp$1.parseExpressionStatement (/home/***/node_modules/acorn/dist/acorn.js:966:10)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:730:24)
at Parser.pp$1.parseBlock (/home/***/node_modules/acorn/dist/acorn.js:981:25)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:709:33)
at Parser.pp$1.parseTopLevel (/home/***/node_modules/acorn/dist/acorn.js:638:25)
at Parser.parse (/home/***/node_modules/acorn/dist/acorn.js:516:17)
at Object.parse (/home/***/node_modules/acorn/dist/acorn.js:3098:39)
@ ./~/z-schema/src/ZSchema.js 12:24-56
ERROR in ./~/z-schema/src/schemas/hyper-schema.json
Module parse failed: /home/***/node_modules/z-schema/src/schemas/hyper-schema.json Unexpected token (2:13)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:13)
at Parser.pp$4.raise (/home/***/node_modules/acorn/dist/acorn.js:2221:15)
at Parser.pp.unexpected (/home/***/node_modules/acorn/dist/acorn.js:603:10)
at Parser.pp.semicolon (/home/***/node_modules/acorn/dist/acorn.js:581:61)
at Parser.pp$1.parseExpressionStatement (/home/***/node_modules/acorn/dist/acorn.js:966:10)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:730:24)
at Parser.pp$1.parseBlock (/home/***/node_modules/acorn/dist/acorn.js:981:25)
at Parser.pp$1.parseStatement (/home/***/node_modules/acorn/dist/acorn.js:709:33)
at Parser.pp$1.parseTopLevel (/home/***/node_modules/acorn/dist/acorn.js:638:25)
at Parser.parse (/home/***/node_modules/acorn/dist/acorn.js:516:17)
at Object.parse (/home/***/node_modules/acorn/dist/acorn.js:3098:39)
@ ./~/z-schema/src/ZSchema.js 13:24-62
I want to validate swagger yaml/json that I am constructing programmatically and want to pass data to the 'validate' method instead of a file reference(don't want to write data in file and then pass its reference).
Is there any way to do that?
Is the swagger parser capable of parsing the swagger yaml/json stored as an object in node.js?
Can you give me an example?
In the following specification myenum
is supposed to be an integer-valued enumeration, but its enum
property is a list of mixed types. Unexpectedly, the validator does not report any error.
swagger: '2.0'
info:
title: "bad api"
version: "1.0.0"
host: localhost
schemes:
- https
basePath: /path
paths:
"/main":
get:
responses:
200:
description: "Main entry point"
definitions:
myenum:
type: integer
enum:
- not an integer
- 2
Currently swagger-parser uses [email protected].
Could you please update it to use the latest version?
Have there been any thoughts about a synchronous api? I'm currently using swagger-parser to dereference a swagger api definition and then using the resolved one to make api validation middleware. This definition could of course be made asynchronously, but for the purpose of doing an initial setup, doing it asynchronously means some inflexibility or slight performance issues on hot (request time) code. No pressure if you just flat out don't want to support it, I was just curious.
Maybe related to #33, the following schema is valid according to swagger-parser. Note that schema on post has a notExists
property.
swagger: '2.0'
info:
version: 1.0.0
title: Swagger Petstore
paths:
/pets:
post:
description: Creates a new pet in the store
parameters:
- name: pet
in: body
description: Pet to add to the store
required: true
schema:
type: object
required:
- notExists
properties:
name:
type: string
responses:
'200':
description: pet response
schema:
type: object
properties:
name:
type: string
Is it not possible to destructure "allOf" array? I want the object definitions in the array be merged into a single "properties" object.
I'm using v3 to dereference my Swagger spec which is broken out into many separate files. It works to create a single file, however the file is unnecessarily large as everything is inlined. It would be really great if you could configure it to move referenced definitions/responses, etc. to the relevant container keys in the main document, instead of inlining everything.
In other words, rewrite the references to point to local keys in the main document, to avoid the repetition.
If you reference a definition in another file, the parser fails to load it because it doesn't strip before the #
.
# foo.yaml
definitions:
Error:
properties:
error:
type: string
required: ["error"]
# main.yaml
[...]
schema:
$ref: './foo.yaml#/definitions/Error'
Fails with:
// metadata
{
baseDir: "/home/swagger/",
files: [
"/home/swagger/main.yaml",
"/home/swagger/foo.yaml#/definitions/Error"
],
urls: [],
'$refs': {}
}
// error
Error: Error opening file "/home/swagger/foo.yaml#/definitions/Error"
As an aside, I believe that when $ref
references files, it is not compulsory to put a starting .
(this threw me off for a while as I was trying foo.yaml#/definitions/Error
instead of ./foo.yaml#/definitions/Error
. It was only when debugging resolve.js
did I notice:
:14 // Matches anything that starts with "http://" or contains a period (".")
I'm thinking about switching to your library for validation purposes.
Especially since you already using it as testsuite :)
One of the things that blocks me is that I need errors in z-schema format in order to autofix them.
I don't want to parse error string because it too unreliable.
Here you can see example of my use case.
Found some behavior which differs from swagger.io validator.
Here is my swagger.json.
Your tool validates it successfully, while swagger.io does not
May be the problem with header in response. Because previous commit validated successfully by swagger.io
The basic example in the README file is referencing a function swagger.parser.parse
but it should really be parser.parse
as described further down. It would also be nice to have the one line require
call as well, since referencing variables which aren't declared in an example without comments needlessly obfuscates things.
The section "The API" is also referring to swagger
when it really means swaggerPath
.
Hi,
I the course of parsing Google's urlshortener api, I noticed that a number of description fields that Google apparently likes to have unescaped double quotes in, are problematic.
eg.
Under definitions.AnalyticsSnapshot.properties.browsers, the description field shows:
Top browsers, e.g. "Chrome"; sorted by (descending) click counts. Only present if this data is available.
Stringified snippet:
"definitions":{"AnalyticsSnapshot":{"properties":{"browsers":{"description":"Top browsers, e.g. "Chrome"; sorted by (descending) click counts. Only present if this data is available."
This plays havoc with my ability to save the stringified swagger file in a db (mysql) and then retrieve it afterwards. I do this after processing the swagger as an insurance in case I missed something. I suppose I could eliminate this, but I don't want to just yet. I cannot use db escape functions because they would just get handled like all the valid double quotes.
OpenAPI allows extensions to the Swagger Schema with "x-" attribute name pattern. Swagger Parser 3.4.1 throws a ValidationError. Swagger CLI accepts extensions.
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#patterned-objects
is it possible to make it so, that the parser only resolves external references?
Besides validation, the parser works great for resolving external references, so that I can gather all the external files in one swagger file.
However, I would like to reference some things in the definitions part of the file, so that the file size doesn't get too big.
Thanks for doing a great job!
Spaces in $ref
field (even for local references) are replaced with %20
after bundle
. At the same time definitions are keep unchanged.
Check out this minimal example: https://tonicdev.com/568d54ee61bef80d0022d2a7/569a1141545e300d002fae3b
Is there a way to get all the error's captured while we validate the swagger? Currently it only catches the first schema validation error.
There might be a case where multiple #ref
might be broken. It would be nice to have a way in which we could catch all possible schema validation errors in one single validate call.
First of all thank you for using and promoting my project.
To fix APIs-guru/openapi-directory/issues/19 I changed directory structure, so instead of top level all specs moved into APIs folder.
I also switched from JSON to YAML.
It breaks your test suite and I see 3 possibilities to fix it:
When you make your decision I can assist with migration.
P.S. I also create a badge to show number of APIs in collection: https://apis-guru.github.io/api-models/apis_in_collection_banner.svg
Maybe you can use it in your README or have an idea about text that better suite this badge.
I am using a swagger-parser in order to validate a special json file. I have the following error:
Swagger schema validation failed.
Additional properties not allowed: usbMemoryTotalBytes,flashMemoryAvailBytes,model,powerSource,firmwareVersionMain,boardVersion,supplyVoltage,serialNumber,id,runTime,vendor,boardVoltage,frequencySource,flashMemoryTotalBytes,boardTemperature,CPUFrequency,ramSize,hardwareVersion,usbMemoryAvailBytes,externalAntennaStatus at #/definitions//receiver/information//properties/information
JSON_OBJECT_VALIDATION_FAILED
Error: Swagger schema validation failed.
Additional properties not allowed: usbMemoryTotalBytes,flashMemoryAvailBytes,model,powerSource,firmwareVersionMain,boardVersion,supplyVoltage,serialNumber,id,runTime,vendor,boardVoltage,frequencySource,flashMemoryTotalBytes,boardTemperature,CPUFrequency,ramSize,hardwareVersion,usbMemoryAvailBytes,externalAntennaStatus at #/definitions//receiver/information//properties/information
JSON_OBJECT_VALIDATION_FAILED
at http://127.0.0.1:8080/www/js/bundle.min.js:11:318
at http://127.0.0.1:8080/www/js/bundle.min.js:50:316
SyntaxError: Swagger schema validation failed.
Additional properties not allowed: usbMemoryTotalBytes,flashMemoryAvailBytes,model,powerSource,firmwareVersionMain,boardVersion,supplyVoltage,serialNumber,id,runTime,vendor,boardVoltage,frequencySource,flashMemoryTotalBytes,boardTemperature,CPUFrequency,ramSize,hardwareVersion,usbMemoryAvailBytes,externalAntennaStatus at #/definitions//receiver/information//properties/information
JSON_OBJECT_VALIDATION_FAILED
at Function.syntax (http://127.0.0.1:8080/dist/swagger-parser.min.js:284:318)
at validateSchema (http://127.0.0.1:8080/dist/swagger-parser.min.js:20:254)
at http://127.0.0.1:8080/dist/swagger-parser.min.js:8:1921
z-schema validation error: JSON_OBJECT_VALIDATION_FAILED
at ZSchema.getLastError (http://127.0.0.1:8080/dist/swagger-parser.min.js:2047:3479)
at validateSchema (http://127.0.0.1:8080/dist/swagger-parser.min.js:20:158)
at http://127.0.0.1:8080/dist/swagger-parser.min.js:8:1921
The swagger validate give me those error when it tries to validate the following json lines:
"definitions": {
"/receiver/information/": {
"description": "Receiver Information Resources",
"x-permission": ["GET"],
"properties": {
"information": {
"externalAntennaStatus" :{
"title":"#/basic/Receiver/Information/externalAntennaStatus"
},
"usbMemoryAvailBytes" :{
"title":"#/basic/Receiver/Information/usbMemoryAvailBytes"
},
"hardwareVersion" : {
"title":"#/basic/Receiver/Information/hardwareVersion"
},
. . .. . . . .. . . . .. . . .
Unfortunately I have to keep the json file as is. I have to add a special rule in order to "validate" my special json file, without put the x-property in json file.
Where is the best place to add this special rule into swagger-parser ? How can it could be ?
I am working in local.
Hello,
I'm starting with swagger, but I'm deeply familiar with the concept of API contracts (swagger, RAML, API Blueprint) as well as JSON Schema. I've tried your online example and I used to built-in petstore example:
As far as I see, this is not pet.yaml
, but pet.json
. It's not a big difference, but it's very misleading. Especially, that what this tool generates is not just a JSON. It's JSON Schema file. And JSON schema has its own extraordinary big tool stack (far more than just swagger).
So the issue here is a wrong file extension.
Is there a way to pass in a YAML string to parse
? You can pass a YAML file, or a JSON object, but not YAML string. If not, this would be very handy :)
(Awesome package, by the way. 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.