Learning ExpressJS here.
I have a get
route that expects query params i.e.
app.get('/api', (req, res) => {
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona
returns 200 with the res.body as:
{
"name": "Messi",
"age": "31",
"club": "Barcelona"
}
Question
How could I write a custom validation where:
- If the requested query param doesn't exist: status 400
- If any of the params are missing i.e (name, age, club) return a response saying that whichever missing param (name, age, and/or age) is required
Learning ExpressJS here.
I have a get
route that expects query params i.e.
app.get('/api', (req, res) => {
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
On postman the following http://localhost:5000/api?name=Messi&age=31&club=Barcelona
returns 200 with the res.body as:
{
"name": "Messi",
"age": "31",
"club": "Barcelona"
}
Question
How could I write a custom validation where:
- If the requested query param doesn't exist: status 400
- If any of the params are missing i.e (name, age, club) return a response saying that whichever missing param (name, age, and/or age) is required
3 Answers
Reset to default 6The above answers are correct, but as someone who has worked with scalable and maintenable APIs, I'd remend standardizing the validation process of you API using JSON Schemas to define the expected input, and AJV to validate these schemas.
Example usage:
const Ajv = require('ajv');
const express = require('express');
const app = express();
app.get('/api', (req, res) => {
// define precisely the expected shape of the request
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'string' },
club: { type: 'string' }
},
required: ['name', 'age', 'club']
}
// validate the request
const ajv = new Ajv();
const valid = ajv.validate(schema, req.query);
if(!valid) res.status(400).send(ajv.errors);
// request is valid. Do whatever
res.send(req.query);
})
app.listen(8080, () => console.log('Server listening on port 8080'));
Response to /api
:
[
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "name"
},
"message": "should have required property 'name'"
}
]
Response to /api?name=messi&age=10&club=barcelona
:
{
"name": "messi",
"age": "10",
"club": "barcelona"
}
Yes it takes a little bit more code, but trust me, it's the way to go if you want to prepare your app for plex and scalable API validation.
You can build an easy validation middleware.
function validateQuery(fields) {
return (req, res, next) => {
for(const field of fields) {
if(!req.query[field]) { // Field isn't present, end request
return res
.status(400)
.send(`${field} is missing`);
}
}
next(); // All fields are present, proceed
};
}
app.get('/api', validateQuery(['name', 'age', 'club']), (req, res) => {
// If it reaches here, you can be sure that all the fields are not empty.
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
You can also use a third party module for validating requests.
- Express Validator
- Express Superstruct (I'm the author)
You need to check value of every params value
If(typeof req.query.name == 'undefined' )
{ res.status(400).send('name is missing') }
Check for every value