0
0
Expressframework~30 mins

Request and response schemas in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Request and Response Schemas in Express
📖 Scenario: You are building a simple Express server that handles user data. To keep your server organized and safe, you want to define clear rules for what the server expects to receive in requests and what it sends back in responses.
🎯 Goal: Create an Express server with a route /user that accepts a POST request with a JSON body matching a user schema, and responds with a JSON confirming the received data using a response schema.
📋 What You'll Learn
Create an Express app
Define a user data schema for the request body with name (string) and age (number)
Create a POST route /user that validates the request body against the schema
Send a JSON response confirming the received user data
💡 Why This Matters
🌍 Real World
Defining request and response schemas helps keep APIs clear and prevents errors by ensuring data is what the server expects.
💼 Career
Backend developers often define and validate request and response schemas to build reliable and maintainable APIs.
Progress0 / 4 steps
1
Setup Express app and user data schema
Create an Express app by importing express and calling express(). Then create a constant called userSchema that is an object with keys name set to "string" and age set to "number".
Express
Need a hint?

Use require('express') to import Express and call express() to create the app. Define userSchema as an object with the exact keys and string values.

2
Add JSON body parsing middleware
Add middleware to the Express app to parse JSON request bodies by calling app.use(express.json()).
Express
Need a hint?

Use app.use(express.json()) to enable JSON parsing for incoming requests.

3
Create POST /user route with request validation
Create a POST route /user using app.post. Inside the route handler, get req.body and check if name is a string and age is a number. If valid, respond with JSON containing message: "User received" and the user data. If invalid, respond with status 400 and JSON { error: "Invalid user data" }.
Express
Need a hint?

Use app.post('/user', (req, res) => { ... }). Inside, check types with typeof. Send success JSON with res.json or error with res.status(400).json.

4
Start the server on port 3000
Add code to start the Express server listening on port 3000 by calling app.listen(3000).
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.