Provides a simple example demonstrating how express-openapi-validator can be used to automatically validate api requests.
# 1. clone this repo
git clone https://github.com/cdimascio/express-openapi-validator-example
# 2. install dependencies
npm install
Start the Api server
npm start
Try the out the following requests.
The express-openapi-validator automatically validates each request against an openapi 3 specification. If a request is does not match the spec, express-openapi-validator automatically returns an appropriate error response.
ccurl -s http://localhost:3000/v1/pets/as |jq
{
"errors": [
{
"path": ".params.id",
"message": "should be integer",
"errorCode": "type.openapi.validation"
}
]
}
curl -s http://localhost:3000/v1/pets\?limit\=1 |jq
{
"errors": [
{
"path": ".query.limit",
"message": "should be >= 5",
"errorCode": "minimum.openapi.validation"
},
{
"path": ".query.test",
"message": "should have required property 'test'",
"errorCode": "required.openapi.validation"
}
]
}
curl -s --request POST \
--url http://localhost:3000/v1/pets \
--header 'content-type: application/xml' \
--data '{
"name": "test"
}' |jq
"message": "unsupported media type application/xml",
"errors": [
{
"path": "/v1/pets",
"message": "unsupported media type application/xml"
}
]
}
λ curl -s --request POST \
--url http://localhost:3000/v1/pets \
--header 'content-type: application/json' \
--data '{
}'|jq
{
"message": "request.body should have required property 'name'",
"errors": [
{
"path": ".body.name",
"message": "should have required property 'name'",
"errorCode": "required.openapi.validation"
}
]
}
curl -XPOST http://localhost:3000/v1/pets/10/photos -F file=@app.js|jq
{
"files_metadata": [
{
"originalname": "app.js",
"encoding": "7bit",
"mimetype": "application/octet-stream"
}
]
}
Using ApiKeyAuth
curl -XPOST http://localhost:3000/v1/pets |jq
{
"message": "'X-API-Key' header required.",
"errors": [
{
"path": "/v1/pets",
"message": "'X-API-Key' header required."
}
]
}
with the api key and security handler
curl -XPOST http://localhost:3000/v1/pets --header 'X-Api-Key: XXXXX' --header 'content-type: application/json' -d '{"name": "carmine"}' |jq
{
"name": "sparky"
}