Excuse me if this question seems obvious, but I am new to Express, Node, and Swagger.
I have written a Swagger specification for an API.
Are there tools in which you can pass a request to a Swagger documented API along with the Swagger.json file to validate that the required parameters are there, that the enum values for those parameters are correct, etc.?
Something akin to:
validator.validate ("./swagger.json", req, function (req, res, err) {
if (err) {
res.status('400').send(err.message());
}
else {
// Call my controller
swaggerController(req, res);
}
});
I believe there is, but it's difficult to find or I'm not looking for the correct thing.
Yes, you can do this. There is a generator project that does exactly this, express-no-stress. Get it here:
When using it, each API request will be validated against your Swagger API description, provided by you, in Api.yaml.
For example, to validate the body of a POST request to /examples, you can do the following:
Edit Api.yaml
...
definitions:
# define the example body i.e. require the property name
ExampleBody:
type: object
title: example
required:
- name
properties:
name:
type: string
description: The example name
paths:
# define your /examples POST endpoint
# reference the ExamplesBody definition from above
/examples:
post:
tags:
- Examples
description: Create a new example
parameters:
- name: example
in: body
description: number of items to skip
required: true
schema:
$ref: "#/definitions/ExampleBody"
responses:
200:
description: Returns all examples
...
Next, in the Node.js code create a route handler for POSTs to /examples
e.g.
app.post('/examples', function (req, res) {
/* your handler logic here */
/* no need to validate the request payload. it will be done automatically */
});
Note: include only your handler logic. Body validation will be handled automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With