Request and response schemas help you define the shape of data your server expects and sends. This keeps your app organized and avoids errors.
0
0
Request and response schemas in Express
Introduction
When you want to check that incoming data from users is correct before using it.
When you want to make sure the data your server sends back is always in the right format.
When you want to document what data your API accepts and returns for other developers.
When you want to catch mistakes early and give clear error messages.
When you want to keep your code clean and easy to maintain.
Syntax
Express
const schema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' }
},
required: ['name', 'age'],
additionalProperties: false
};This example shows a simple schema for an object with name and age.
You can use libraries like ajv to validate data against these schemas.
Examples
This schema checks that the request body has a username and password, both strings.
Express
const requestSchema = {
type: 'object',
properties: {
username: { type: 'string' },
password: { type: 'string' }
},
required: ['username', 'password'],
additionalProperties: false
};This schema defines the shape of the response your server sends back.
Express
const responseSchema = {
type: 'object',
properties: {
success: { type: 'boolean' },
message: { type: 'string' }
},
required: ['success'],
additionalProperties: false
};Sample Program
This Express app uses a schema to check incoming user data. If data is wrong, it sends an error. If correct, it sends a success message.
Express
import express from 'express'; import Ajv from 'ajv'; const app = express(); const ajv = new Ajv(); app.use(express.json()); const userSchema = { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name', 'age'], additionalProperties: false }; const validateUser = ajv.compile(userSchema); app.post('/user', (req, res) => { const valid = validateUser(req.body); if (!valid) { return res.status(400).json({ error: 'Invalid user data' }); } res.json({ success: true, message: `User ${req.body.name} added.` }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always validate request data to avoid crashes or security issues.
Response schemas help keep your API consistent and easy to use.
Use tools like ajv for easy schema validation in Express.
Summary
Request and response schemas define the expected data shapes.
They help catch errors early and keep your API clear.
Use validation libraries to check data against schemas in Express.