Bird
Raised Fist0
Expressframework~20 mins

Request and response schemas in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Express Schema Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Express route when sending a valid JSON body?

Consider this Express route that expects a JSON body with a name property and responds with a greeting.

app.post('/greet', (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }
  res.json({ message: `Hello, ${name}!` });
});

What will the response be if the client sends { "name": "Alice" } as JSON?

Express
app.post('/greet', (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(400).json({ error: 'Name is required' });
  }
  res.json({ message: `Hello, ${name}!` });
});
A{"error":"Name is required"}
B{"message":"Hello, Alice!"}
CStatus 500 Internal Server Error
DEmpty response with status 200
Attempts:
2 left
💡 Hint

Think about what the route does when name is present in the request body.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a JSON schema middleware for validating a request body in Express?

You want to validate that the request body contains a username (string) and age (number) before processing it. Which middleware definition is correct?

A
const schema = {
  username: 'string',
  age: 'number',
  required: ['username', 'age']
};
B
const schema = {
  type: 'array',
  items: {
    username: 'string',
    age: 'number'
  }
};
C
const schema = {
  type: 'object',
  properties: {
    username: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['username', 'age'],
  additionalProperties: false
};
D
const schema = {
  type: 'object',
  properties: {
    username: 'string',
    age: 'number'
  },
  required: ['username', 'age']
};
Attempts:
2 left
💡 Hint

JSON schema requires type and properties keys with proper types.

🔧 Debug
advanced
2:00remaining
What error does this Express route produce when the request body is missing the required field?

Given this route using a JSON schema validator middleware:

app.post('/user', validateSchema(schema), (req, res) => {
  res.json({ success: true });
});

If the client sends {} (empty body) and schema requires a username, what error will occur?

Express
const schema = {
  type: 'object',
  properties: {
    username: { type: 'string' }
  },
  required: ['username'],
  additionalProperties: false
};
ASyntaxError thrown by Express
B500 Internal Server Error due to missing property
C200 OK with empty JSON response
D400 Bad Request with validation error message
Attempts:
2 left
💡 Hint

Think about how validation middleware handles missing required fields.

❓ state_output
advanced
2:00remaining
What is the response body after this Express route processes a request with extra fields?

Consider this route that validates request body against a schema disallowing extra fields:

const schema = {
  type: 'object',
  properties: {
    email: { type: 'string' }
  },
  required: ['email'],
  additionalProperties: false
};

app.post('/subscribe', validateSchema(schema), (req, res) => {
  res.json({ subscribed: true });
});

If the client sends { "email": "user@example.com", "age": 30 }, what will the response be?

A400 Bad Request with error about additional properties
B200 OK with {"subscribed": true}
C500 Internal Server Error
D200 OK with empty JSON {}
Attempts:
2 left
💡 Hint

Check what additionalProperties: false means in JSON schema.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of request and response schemas in Express applications?

Choose the most accurate description of why request and response schemas are used in Express apps.

AThey ensure data sent and received matches expected formats, improving reliability and security.
BThey allow Express to run faster by skipping data parsing.
CThey replace the need for any manual error handling in routes.
DThey automatically generate HTML forms for user input based on schema definitions.
Attempts:
2 left
💡 Hint

Think about the purpose of validating data in web applications.

Practice

(1/5)
1. What is the main purpose of using request and response schemas in an Express app?
easy
A. To define and validate the shape of data sent and received
B. To speed up the server response time
C. To style the API responses with colors
D. To automatically generate HTML pages

Solution

  1. Step 1: Understand the role of schemas

    Request and response schemas specify what data structure is expected, helping to validate inputs and outputs.
  2. Step 2: Identify the main benefit

    This validation helps catch errors early and keeps the API clear and consistent.
  3. Final Answer:

    To define and validate the shape of data sent and received -> Option A
  4. Quick Check:

    Schema purpose = validation [OK]
Hint: Schemas check data shape to avoid errors [OK]
Common Mistakes:
  • Thinking schemas improve speed directly
  • Confusing schemas with styling tools
  • Assuming schemas generate HTML automatically
2. Which of the following is the correct way to use a schema validation middleware in Express for a POST request body?
easy
A. app.get('/user', validateSchema, (req, res) => { ... })
B. app.post('/user', validateSchema, (req, res) => { ... })
C. app.post('/user', (req, res) => validateSchema(req.body))
D. app.use(validateSchema('/user'))

Solution

  1. Step 1: Identify correct HTTP method and middleware usage

    Schema validation middleware should be used in the route handler chain, typically for POST requests when validating request bodies.
  2. Step 2: Check syntax correctness

    app.post('/user', validateSchema, (req, res) => { ... }) correctly places the middleware function before the route handler for POST '/user'.
  3. Final Answer:

    app.post('/user', validateSchema, (req, res) => { ... }) -> Option B
  4. Quick Check:

    Middleware before handler for POST = B [OK]
Hint: Middleware goes between route and handler [OK]
Common Mistakes:
  • Using GET instead of POST for body validation
  • Calling middleware inside handler instead of chaining
  • Using app.use incorrectly with route path
3. Given this Express route using Joi schema validation middleware:
const schema = Joi.object({ name: Joi.string().required() });
app.post('/data', (req, res, next) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).send(error.message);
  res.send('Valid data');
});
What will the response be if the client sends {} as JSON body?
medium
A. Valid data
B. 500 Internal Server Error
C. 400 Bad Request with error message
D. Empty response with status 200

Solution

  1. Step 1: Analyze schema requirements

    The schema requires a 'name' string field that is mandatory.
  2. Step 2: Check validation result for empty body

    Sending an empty object {} misses the required 'name', so validation fails and error is returned with status 400.
  3. Final Answer:

    400 Bad Request with error message -> Option C
  4. Quick Check:

    Missing required field = 400 error [OK]
Hint: Missing required fields cause 400 error [OK]
Common Mistakes:
  • Assuming empty body passes validation
  • Expecting 500 error on validation failure
  • Thinking success message is sent regardless
4. Consider this Express route snippet with schema validation:
app.post('/item', (req, res) => {
  const { id, price } = req.body;
  if (typeof id !== 'number' || typeof price !== 'number') {
    res.status(400).send('Invalid data');
    return;
  }
  res.send('Item accepted');
});
What is the main bug in this code?
medium
A. It does not stop execution after sending 400 response
B. It uses wrong HTTP method for data submission
C. It does not parse JSON body before accessing req.body
D. It sends response twice causing server crash

Solution

  1. Step 1: Check response flow after validation failure

    After sending 400 response, the code continues and sends 'Item accepted' response, causing multiple responses.
  2. Step 2: Identify missing control flow

    There is no return or else to stop execution after sending error response.
  3. Final Answer:

    It does not stop execution after sending 400 response -> Option A
  4. Quick Check:

    Send response then stop = return [OK]
Hint: Return after res.send to stop code [OK]
Common Mistakes:
  • Ignoring missing return after error response
  • Assuming Express auto-stops after res.send
  • Confusing HTTP method correctness
5. You want to create an Express route that accepts a JSON body with an array of user objects, each having a required 'email' string and optional 'age' number. Which Joi schema correctly validates this request body?
hard
A. Joi.object({ users: Joi.array().required() })
B. Joi.object({ email: Joi.string().required(), age: Joi.number() }).required()
C. Joi.array().items(Joi.string().email().required())
D. Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() }))

Solution

  1. Step 1: Understand the data shape

    The body is an array of user objects, each with required 'email' string and optional 'age' number.
  2. Step 2: Match schema to data shape

    Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() })) defines an array of objects with the correct fields and validations.
  3. Final Answer:

    Joi.array().items(Joi.object({ email: Joi.string().email().required(), age: Joi.number() })) -> Option D
  4. Quick Check:

    Array of objects with required email = A [OK]
Hint: Use array().items(object({...})) for arrays of objects [OK]
Common Mistakes:
  • Using object schema instead of array for array data
  • Validating array of strings instead of objects
  • Missing required email validation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard