Request, Response, and Data Transfer Objects - Textnotes

Request, Response, and Data Transfer Objects


Learn how to implement type-safe API validation in TypeScript using request validation, response validation, and data transfer objects (DTOs). This module explains best practices for building reliable and maintainable APIs

1. Request Validation

Validating incoming requests ensures that API endpoints receive correct data. Libraries like class-validator and class-transformer are commonly used with TypeScript.

Installation


npm install class-validator class-transformer
npm install --save-dev reflect-metadata

Example: DTO for Request


import { IsString, IsInt, Min } from "class-validator";

export class CreateUserDTO {
@IsString()
name: string;

@IsInt()
@Min(18)
age: number;
}

Using in Express


import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";

app.post("/user", async (req, res) => {
const dto = plainToInstance(CreateUserDTO, req.body);
const errors = await validate(dto);
if (errors.length > 0) {
return res.status(400).json(errors);
}
res.json({ message: "User is valid", data: dto });
});

Request validation ensures type-safe and predictable data before reaching business logic.

2. Response Validation

Validating API responses ensures that the outgoing data matches expected types.

Example


import { Expose, plainToInstance } from "class-transformer";

class UserResponseDTO {
@Expose()
name: string;

@Expose()
age: number;
}

app.get("/user/:id", (req, res) => {
const user = { name: "Muni", age: 25, secret: "hidden" };
const responseDto = plainToInstance(UserResponseDTO, user, { excludeExtraneousValues: true });
res.json(responseDto); // secret field is excluded
});

Response validation ensures only allowed fields are sent to clients, improving security and data consistency.

3. Data Transfer Objects (DTOs)

DTOs are classes or types that define the shape of data sent between layers of an application. They improve type safety and maintainability.

Benefits of DTOs

  1. Clear contract for request and response data
  2. Type-safe access to properties
  3. Easier validation and transformation

Example


export class UpdateUserDTO {
name?: string;
age?: number;
}

Using DTOs, you can safely accept partial updates and validate only the fields that are present.

Conclusion

Implementing API validation and DTOs in TypeScript ensures type-safe requests and responses. Using DTOs with validation libraries improves code reliability, reduces runtime errors, and provides a clean contract between API layers.