How to Validate Incoming HTTP API Requests

Brew #6·November 7, 2026·7 minutes read

Request validation is the process of checking that incoming HTTP request data conforms to the structure and constraints expected by an API endpoint before the application processes it.

Missing fields, incorrect types, unexpected properties, or unbounded values can cause:

  • Application errors when business logic receives data it does not expect.
  • Unintended data to be passed to application services or persistence layers.
  • Excessive resource consumption from values such as large pagination limits or oversized request bodies.

The short answer

The most common way to validate incoming HTTP API requests is to:

  1. Check the request's Content-Type and reject body formats the endpoint does not support.
  2. Parse the request body using the appropriate parser with an explicit size limit.
  3. Define a validation schema describing the expected structure, types, formats, and constraints of the headers, request body, route parameters, and query parameters.
  4. Use a middleware to validate the request against the schema before executing business logic and return an HTTP 400 Bad Request if validation fails.
  5. Forward the validated data to the next component instead of using the original request values.

Validating the content type

Before processing the incoming request, the endpoint should first define which media types it accepts based on the value of the Content-Type header, and reject unsupported formats with an HTTP 415 Unsupported Media Type.

For example, a JSON-only endpoint should reject any request whose Content-Type header doesn't contain application/json with an HTTP 415 Unsupported Media Type, even if its body contains valid JSON.

import type { RequestHandler } from 'express';

export const requireJson: RequestHandler = (req, res, next) => {
  if (!req.is('application/json')) {
    res.status(415).json({
      error: {
        code: 'UNSUPPORTED_MEDIA_TYPE',
        message: 'Expected application/json'
      }
    });
    return;
  }
  next();
};

Parsing the request body

HTTP requests using methods such as POST, PUT, or PATCH may contain a message body that must be parsed into a format the application understands, according to their Content-Type header.

The parser must also reject invalid message bodies with the appropriate HTTP status code:

  • 400 Bad Request for malformed bodies.
  • 413 Content Too Large for bodies exceeding the allowed size.

‼️ A syntactically correct body may still contain invalid or unexpected values and must be validated before business logic uses it.

For example, Express.js provides express.json() for JSON bodies that can be configured with an explicit body-size limit:

express.json({ limit: '16kb' });

Defining a request validation schema

Incoming request data must be validated against the API contract before the application processes it.

This includes, when applicable:

  • The message body, when present.
  • Route parameters like resource identifiers, slugs, and other values embedded in the URL.
  • Query parameters like pagination, filtering, sorting, and other request options.
  • HTTP headers like idempotency keys or language preferences.

This is done using a validation schema that defines which fields are accepted, whether they are required or optional, and the constraints their values must satisfy.

These constraints include:

  • The expected data types and formats.
  • The allowed values and numeric ranges.
  • The minimum and maximum string lengths.
  • The maximum array sizes and numbers of repeated values.

For example, if your API is built with Express.js, you could use Zod to create a schema that defines the same properties as the ones present in the req request object.

import { z } from 'zod';

const schema = z.object({
  headers: z.object({ /* ... */ }),
  params: z.object({ /* ... */ }),
  query: z.object({ /* ... */ }),
  body: z.object({ /* ... */ }),
});

Handling unexpected properties

Incoming requests may contain unknown properties that aren't defined in the API contract.

In this case, the endpoint can either:

  • Reject the request to enforce a strict contract and help clients identify unsupported properties.
  • Accept the request to make the endpoint more tolerant while stripping away unknown properties before forwarding the request downstream.

For example, in Zod, you can either use:

  • strictObject() to reject objects containing properties that are not explicitly defined in the schema.
  • object() to accept objects containing additional properties while removing them from the validated output.
import { z } from 'zod';

const schema = z.object({
  body: z.strictObject({
    search: z.string().min(1).max(200),
  }),
  query: z.object({
    page: z.string().optional(),
    limit: z.string().optional(),
  }),
});

Coercing and normalizing properties

In some cases, certain properties may need to be coerced or normalized before the application uses them.

Coercion is useful when the type received through HTTP differs from the type the application needs. For example, the value of the query parameter page=2 should be converted into an integer before being used.

Normalization is useful to convert equivalent input values into a consistent format. For example, trimming whitespace from search terms or lowercasing email addresses when the application treats them as case-insensitive.

For example, in Zod, you can use:

  • trim() to normalize strings by removing leading and trailing whitespace.
  • coerce.number() to coerce strings, such as query parameters, into numbers.
import { z } from 'zod';

const schema = z.object({
  body: z.strictObject({
    search: z.string().trim().min(1).max(200),
  }),
  query: z.object({
    page: z.coerce.number().int().min(1).default(1),
    limit: z.coerce.number().int().min(1).max(100).default(25),
  }),
});

Creating a reusable validation middleware

To enforce request validation consistently, you can use a middleware that runs after any required body parsing, validates the incoming request against the endpoint's schema, and either passes the validated data downstream or returns a validation error to the client.

For example, in Express.js, the validation middleware can be implemented as follows:

  1. Validates the various request components using Zod's safeParse() method.
  2. Responds with an HTTP 400 Bad Request if validation fails.
  3. Otherwise, stores the parsed output in the req.payload property.
  4. Calls next() to forward the request to the next component.

Keep in mind that validation may strip unknown properties, convert types, normalize values, or transform the output. Downstream code must therefore use the validated values present in req.payload rather than the original values present in req.body, req.params, and so on.

import type { RequestHandler } from 'express';
import type { ZodType } from 'zod';

export default function requestValidatorMiddleware(schema: ZodType): RequestHandler {
  return function requestValidator(req, res, next): void {
    const result = schema.safeParse({
      body: req.body,
      query: req.query,
      params: req.params,
      headers: req.headers,
    });

    if (!result.success) {
      res.status(400).json({
        error: {
          code: 'INVALID_REQUEST',
          message: 'Invalid request',
          details: result.error.issues.map((issue) => ({
            path: issue.path.join('.'),
            message: issue.message,
          })),
        },
      });
      return;
    }

    req.payload = result.data;

    next();
  };
}

Note that the payload property would need the following TypeScript declaration to work.

declare global {
  namespace Express {
    interface Request {
      payload?: unknown;
    }
  }
}

Applying validation to an API endpoint

Here's what complete request validation would look like in practice for an HTTP POST endpoint.

import express from 'express';
import type { Request, Response, NextFunction } from 'express';
import { z } from 'zod';

declare global {
  namespace Express {
    interface Request {
      payload?: unknown;
    }
  }
}

app.post(
  '/logs/search',

  // 1. Validate the Content-Type header.
  (req: Request, res: Response, next: NextFunction): void => {
    if (!req.is('application/json')) {
      res.sendStatus(415);
      return;
    }
    next();
  },

  // 2. Parse the request body with a size limit.
  express.json({ limit: '16kb' }),

  // 3. Handle body parsing errors.
  (err: unknown, _req: Request, res: Response, next: NextFunction): void => {
    if (err instanceof Error && 'type' in err) {
      if (
        err.type === 'entity.parse.failed' ||
        err.type === 'request.size.invalid'
      ) {
        res.sendStatus(400);
        return;
      }

      if (err.type === 'entity.too.large') {
        res.sendStatus(413);
        return;
      }
    }

    next(err);
  },

  // 4. Validate the request against its schema.
  (req: Request, res: Response, next: NextFunction): void => {
    const schema = z.object({
      body: z.strictObject({
        search: z.string().trim().min(1).max(200),
      }),
      query: z.object({
        page: z.coerce.number().int().min(1).default(1),
        limit: z.coerce.number().int().min(1).max(100).default(25),
      }),
    });

    const result = schema.safeParse({
      body: req.body,
      query: req.query,
      params: req.params,
      headers: req.headers,
    });

    if (!result.success) {
      res.status(400).json({
        details: result.error.issues.map((issue) => ({
          path: issue.path.join('.'),
          message: issue.message
        }))
      });
      return;
    }

    req.payload = result.data;

    next();
  },

  // 5. Process the validated request.
  (req: Request, res: Response): void => {
    /* ... */
  }
);

Not subscribed yet?

BackendBrewery is just getting started, and my first goal is to bring together 1,000 developers who want to build better backends one decision at a time.

Join today, it's free: