skellla / fastify-oas Goto Github PK
View Code? Open in Web Editor NEWFastify OpenAPI plugin.
Home Page: https://www.comebackalive.in.ua/
License: MIT License
Fastify OpenAPI plugin.
Home Page: https://www.comebackalive.in.ua/
License: MIT License
Hi,
Can you provide a sample to use $ref for body or response schema ?
I'm trying lot of thing but nothing works...
Definition.ts
public static Cat = {
$id: 'Cat',
type: 'object',
required: ['id', 'name'],
properties: {
_id: { type: 'string', format: 'uuid' },
name: { type: 'string'},
}
};
CatRoute.ts :
{
method: 'POST',
url: '/api/cat',
handler: addCatController,
schema: addCatSwagger
}
ControllerCat.ts
function addCatController = async (req, reply) => {
try {
const cat = new CatModel(req.body);
return cat.save();
} catch (err) {
console.error(err);
}
}
SwaggerCat.ts
const add = {
description: `Create a new Cat`,
tags: ['cat'],
summary: `Creates new cat with given values`,
body: {
in: 'body',
name: 'body',
description: 'Pet object that needs to be added to the store',
required: true,
schema: {
$ref: 'Cat'
}
}
,
responses: {
200: {
description: 'Successful response',
}
}
};
Any any to accept Cat definition in the body of my put request ?
Same thing for returning one Cat ? (array of Cat is ok, but how we do with only one object in return )
Can I suggest to leave the default basePath
value to be an empty string instead of '/'
? Currently, the servers URL from the response swagger JSON is always having a trailing slash because of the default value and it doesn't have a way to remove it.
This creates a small problem when importing the JSON file into Postman. Postman can read the swagger JSON and automatically generate all API endpoints. However, the issue here is all the endpoints are having double slash due to the server URL having a trailing slash. To illustrate http://localhost:3000//login
.
If we have a way to unset the default basePath or keep the basePath as empty. It would solve the issue.
Default swagger option basePath value:
fastify-oas/lib/openapi/constructor.js
Line 15 in 4e58c5d
Example of my swagger JSON from fastify-oas:
{
"openapi": "3.0.0",
"info": {
"title": "API documentation",
"description": "Test",
"version": "1.0.0"
},
"components": {},
"servers": [
{
"url": "http://localhost:3000/"
}
],
"paths": {
...
(I'm hoping to have a way to remove the trailing slash from the server url)
Hello,
Thank you for your contribution @SkeLLLa
I have a question. It's possible to generate a spec file/documentation/json
to file system? I need it to generate a OpenAPI client in a CI pipeline.
Currently, I'm doing like this:
export const exportOpenApiSpec = (): void =>
app.listen(port, host, (err) => {
if (err) {
app.log.error(err)
process.exit(1)
}
const spec = JSON.stringify(app.oas())
writeFile('api-client/spec.json', spec, (err) => {
if (err) return app.log.error(err)
app.log.info('Exported with success')
process.exit(0)
})
})
It is possible to do it without running a fastify instance?
Thank you
Hello,
Where can I send a PR to upgrade this package to fastify 3.x? GitHub or GitLab?
TY
Swagger:
Content Security Policy: The page’s settings blocked the loading of a resource at eval (“script-src”).
Redoc:
Content Security Policy: The page’s settings blocked the loading of a resource at eval (“script-src”).
Content Security Policy: The page’s settings blocked the loading of a resource at blob:http://localhost/e69d7b8c-3e5b-4efc-a496-b415b0146d56 (“script-src”).
Deprecated Schema Key is not supported.
Expected: A route with a parameter marked as deprecated: true
would get the deprecated key in the resulting open api documentation.
Actual: deprecated
is not in the allowed keys and so is not included in the documentation.
I have a schema like this
{
"type": "object",
"properties": {
"monitor": {
"type": "object",
"properties": {
"status": {
"oneOf": [
{
"type": "string",
"enum": ["ok"]
},
{
"type": "string",
"enum": ["ko"]
}
]
}
},
"required": ["status"]
}
},
"required": ["monitor"]
}
generated with the nice library https://github.com/sinclairzx81/typebox but the generated example looks like
{
"monitor": {}
}
whereas the interactive schema shows monitor* -> status* -> oneOf -> etc
For bigger schema it can be a problem because user easily jump on the example as documentation, and missing attributes are just ignored, MIA...
I am trying to use oneOf for code generation and the output is not what I am expecting. I traced the root cause of the issue and I think is related with fact that fastify-oas is replacing my references.
For example:
fastify.addSchema({
$id: "Cat",
type: "object",
properties: { name: { type: "string" } }
});
fastify.addSchema({
$id: "Dog",
type: "object",
properties: { legs: { type: "integer" } }
});
Used in a route:
animal: {
oneOf: [
"Cat#",
"Dog#"
]
}
As result I am getting for the path:
animal: {
oneOf: [
{
type: "object",
properties: { name: { type: "string" } }
},
{
type: "object",
properties: { legs: { type: "integer" } }
}
]
}
It would be nice to have the option to get the references instead (like using $ref)
I am unable to build using fastify-oas due to typescript being unable to resolve the augmentations made to the route schema. It also appears that the register schema isn't being loaded either.
This module requires fastify
: https://github.com/SkeLLLa/fastify-oas/blob/master/lib/openapi/index.js#L3.
As such, fastify ought to be listed as a peerDependency with an appropriate (and not overly specific) version specification.
Hello,
when updating fastify to v3 i get this error:
Error: fastify-plugin: fastify-oas - expected '>=2.0.0 <2.12.0 || >=2.12.1 <3.0.0' fastify version, '3.0.2' is installed
Hello and thanks.
Here some logs
Error during invocation: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
at validateString (internal/validators.js:107:11)
at Object.dirname (path.js:1121:5)
at resolve (webpack-internal:///../node_modules/app-root-path/lib/resolve.js:82:22)
at module.exports (webpack-internal:///../node_modules/app-root-path/lib/app-root-path.js:6:20)
at Object.eval (webpack-internal:///../node_modules/app-root-path/index.js:4:18)
at eval (webpack-internal:///../node_modules/app-root-path/index.js:5:30)
at Object.../node_modules/app-root-path/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:3569:1)
at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
at eval (webpack-internal:///../node_modules/fastify-oas/lib/openapi/constructor.js:4:14)
at Object.../node_modules/fastify-oas/lib/openapi/constructor.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5263:1)
at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
at eval (webpack-internal:///../node_modules/fastify-oas/lib/openapi/index.js:1:21)
at Object.../node_modules/fastify-oas/lib/openapi/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5274:1)
at __webpack_require__ (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:20:30)
at eval (webpack-internal:///../node_modules/fastify-oas/lib/index.js:2:17)
at Object.../node_modules/fastify-oas/lib/index.js (/Users/dalisoft/Desktop/Dev Env from null/fastify-dev-env/functions-build/server.js:5252:1)
Hi,
First of all, thanks for great plugin, I am new to Fastify and on my way to create the first API system on it.
However, after many tries I cannot setup swagger to use Bearer auth, can you please give some example on how to archive that?
Many thanks.
I've defined an object property in response schema as below:
taxes: {
type: 'string',
additionalProperties: {
type: 'number'
}
}
The JS object property value in response data is like
taxes: { stampDuty: 0.12 }
Expected data in response:
"taxes": {
"stampDuty": 0.12
}
Actual data in response:
"taxes": "[object Object]"
module.exports = fp(
async (fastify, opts) => {
return openapi(fastify, opts);
},
{
fastify: '<2.12.0',
name: 'fastify-oas',
},
);
... correct plz
Hi,
Need help to understand what does it means by "Unlike regular OpenAPI spec you'll still need some options from swagger 2.0" from https://github.com/SkeLLLa/fastify-oas#openapi
What is this "some options" to be precise?
I have difficulty using this plug-in at the moment... browsing to base_url/documentation return 404. Appreciate if it is possible, please upload an example illustrating how petstore in openapi version 3.0 can be serve from fastify-oas? Understood that this plugin only show the document (ReDoc?) and will not implement the spec.
Thanks.
.. or extend Fastify schema?
Hiya
I notice I can include a single request example by using the example
property on the body.
But what if I want multiple?
Can I propose the allowing of a property like responseExamples
that would set the content[mediaType].examples
property, similar to the way example
is handled in https://github.com/SkeLLLa/fastify-oas/blob/master/lib/helpers.js#L98
Alternatively use the examples
array as is provided, and extract the name property:
else if (body.examples) {
dst.content[mediaType].examples = Object.fromEntries(
body.examples.map(({ name, ...rest }) => [name, rest])
);
delete body.examples;
}
The following throws error even though it is in the spec https://swagger.io/specification/#:~:text=%222.0%22%20.)-,Format,%7B
{
type: 'number'
format: 'double'
}
Awesome library! I have completely autogenerated docs thanks to this repo 💪
One thing I believe I have stumbled across is that you can't have multiple types e.g:
Note:
SwaggerHelper.modelToSwaggerProps
is just a method that maps Sequelize model datatypes to Swagger datatypes
const {ProjectUsers, Projects} = require('my-sequelize-model-repo')
fastify.addSchema({
$id: 'projectUser',
type: 'object',
properties: Object.assign(
SwaggerHelper.modelToSwaggerProps(ProjectUsers, true)[ProjectUser],
{
Project: {
type: ['object', 'null'],
nullable: true,
properties: SwaggerHelper.modelToSwaggerProps(Projects)[Project]
}
}
)
})
Which will generate...
{
'$id': 'projectUser',
type: 'object',
properties: {
id: { type: 'integer' },
user_id: { type: 'integer' },
project_id: { type: 'integer' },
notes: { type: 'string' },
occurred_at: { type: 'string', format: 'date-time' },
created_at: { type: 'string', format: 'date-time' },
updated_at: { type: 'string', format: 'date-time' },
deleted_at: { type: 'string', format: 'date-time' },
Project: {
type: ['object', 'null'],
nullable: true,
properties: {
id: { type: 'integer' },
name: { type: 'string' }
}
}
}
}
Note the attempt to get the child association (Project) to be either an object
or null
I think this was also caught in another implementation: AfterShip/swagger-ajv#19
This has got me in quite the pickle because Ajv (the default json validator with fastify) isn't happy with if the Project model is null if I just keep the type as 'object'. This configuration works in the API response through Ajv - but it breaks in swagger docs
Hi !
The index.d.ts seems outdated : could you remove it from the repository ?
I am wondering how to get the swagger-ui for my server let me do an 'upload-file' request/form. Any ideas or suggestions? I have gotten this type of thing to work in non-js projects that have swagger docs before.
export const opts: RouteShorthandOptions = {
schema: {
tags: ["organization"],
params: baseParamsSchema,
response: {
200: organizationSchema,
},
},
preValidation: [],
preHandler: [],
};
results in
Type
{ tags: string[];
params: {
description: string;
type: string;
properties: {
organizationId: {
type: string;
title:
string;
};
};
required: string[]; $schema: string; };
response: {
200: {
description: string;
type: string;
properties: { ...; };
required: string[];
$schema: string;
};
};
}
is not assignable to type 'FastifySchema'.
Object literal may only specify known properties,
and 'tags' does not exist in type 'FastifySchema'.
But tags is a part of schema in fastify 3.x, can u resolve? To circumvent I am using @ts-ignore
Context
node version: v15.12.0
fastify version: >=^3.14.0
fastify-oas: ^3.0.8
os: Windows, Ubuntu WSL
Please :)
In my project my intention is to configure fastify-swagger with OpenAPI version 3.0.0 with the following configuration:
I am using fastify-oas as fastify plugin such that my existing configuration does not need to alter.
const swaggerConfig = {
swagger: {
info: {
title: `${constants.SERVICE_NAME.toUpperCase()} swagger`,
description: `NetApp ${constants.SERVICE_NAME.toUpperCase()} service API.`,
version: '1.0.0'
},
externalDocs: {
url: 'https://swagger.io',
description: 'Find more info here'
},
schemes: [`${schema}`],
consumes: ['application/json'],
produces: ['application/json'],
tags: [
{ name: 'persistence', description: 'foo' },
{ name: 'index', description: 'bar'}
],
securityDefinitions: {
Authorization_Token: {
type: 'apiKey',
name: 'Authorization',
in: 'header'
}
}
},
exposeRoute: true,
routePrefix: `${constants.EXTERNAL_PATH}/api-docs`
};
fastify.register(require('fastify-oas'), swaggerConfig );
Actually I was trying to following the following link here (https://github.com/fastify/fastify-swagger/blob/master/examples/dynamic-openapi.js).
However somehow I am not able to succeed, always it shows the error that it's not able to load the swagger. Not seeing any error in the console. The error is like below screen shot:
Any clue how can I debug would be helpful how can I proceed with debugging this.
One interesting point is: as I am removing arbitrarily some portion of the schema just to see if I can pin point by trial and error, it's start working!
So if there a way to bit systematically debug it, would be great.
Thanks,
Pradip
How to use this awesome plugin with custom swagger ui ?
Is there any change to we have it ?
Hi there !
I just noticed that when tagging an attribute of the body as required, in the swagger html view, the little red star
that indicates that the field is required in the body doesn't show on the given field.
Commenting this line in the code solves the problem and the required fields display as expected in the swagger view.
Do you have any insight on this behavior ? I mean, why deleting the body.required
?
Thanks in advance for your answer ;)
And thank you for your efforts on this plugin and keep up the good work ! 👍
made a quick test....
changed fastify: '>=2.0.0 <2.12.0 || >=2.12.1 <4.0.0'
when opening swagger ui, and clicking on any route having a $ref
in the schema:
fastify changes: https://github.com/fastify/fastify/blob/master/docs/Migration-Guide-V3.md#changed-schema-substitution-2023
I originally thought this might be related to #30, however I now do not think it is.
I'm using Fastify v2.14.1, and I instantiate my own AJV and configure it using .addSchema(...). I then use the $id references from my manually loaded schemas when creating my route schemas. This works fine in Fastify, and I can tell the schemas are being validated at runtime.
However, when using the plugin UI, and navigating into a particular route, I get the following error, when the schema reference is attempted to be resolved.
Resolver error at paths./events.post.requestBody.content.application/json.schema.properties.rulesets.items.$ref
Could not resolve reference: Failed to fetch
The $ref I am using is a full URL with hostname, but I would expect the plugin to lookup the reference using AJV where it is registered, instead of attempting to fetch. Perhaps this is the wrong expectation?
Hello there,
are you aware of this issue?
GHSA-p6vg-p826-qp3v
I've tried using addModels: true
param to enable models view on the UI, although It seems to be not really documented and neither having any effects when setting this to true.
Hi. Thanks for the great library.
I noticed a bug when using common schemas via $ref
. Being a fastily schema, they'll have an $id
property. Normally this gets trimmed out in the allowedProps
function with objects/properties but that doesn't seem to happen with array/items.
Using following schema:
fastily.addSchema({
$id: 'MyBusinessObject',
type: 'object',
properties: {}
})
const schema = {
type: 'array',
items: {
$ref: 'MyBusinessObject#'
}
};
The following oas document for this section is generated, which raises warnings for having additional properties, $id:
{
"type": "array",
"items": {
"$id": "MyBusinessObject",
"type": "object",
"properties": {}
}
}
I've got a fix for it and will be sending a PR shortly.
Is there a way to only expose one of the two UIs? I prefer one over the other and would like to share specific doc URLs with team members and it would be simpler if I could disable one of the two and use /documentation/index.html
for the only one loaded up.
how to add tags in routes
In AJV you can add custom properties and validation rules. However, when you generate the json/yaml through fastify-oas, these will be included. Is there a way to filter these?
Api schema may change such as server information on openapi 3 base on multiple domains.
Not static one during register plugin.
How could we handle it ?
"servers": // ??,
Hi,
If it's possible - I'll be grateful, if it is - I can't find how to do it:
I would like the server to serve the OAS json/yaml, but not the SwaggerUI/ReDoc UIs.
Is it supported?
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.