NestJS HTTP Methods

HTTP methods define the type of action a client wants to perform. When a client sends a request, the method tells the server whether the client wants to read, create, update, or delete something. NestJS maps each HTTP method to a specific decorator, giving your controller methods a clear, readable structure.

The Standard HTTP Methods

Method   | Purpose               | Typical Response
---------|-----------------------|-------------------
GET      | Read data             | 200 OK
POST     | Create new data       | 201 Created
PUT      | Replace entire record | 200 OK
PATCH    | Update part of record | 200 OK
DELETE   | Remove a record       | 200 OK or 204 No Content
HEAD     | Like GET, no body     | 200 OK (headers only)
OPTIONS  | Ask what methods work | 200 OK

GET — Reading Data

GET requests retrieve data. They do not change anything on the server. A browser entering a URL, a dashboard loading a list, or a mobile app fetching a user profile — all use GET.

@Get()
findAll() {
  return this.productsService.findAll();
}

@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
  return this.productsService.findOne(id);
}

POST — Creating Data

POST requests send data to the server to create a new resource. The body carries the new data. NestJS returns status 201 by default for POST methods.

@Post()
create(@Body() createProductDto: CreateProductDto) {
  return this.productsService.create(createProductDto);
}

PUT — Full Replacement

PUT requests replace an existing resource entirely. The client sends a complete object. Any field not included in the request body gets overwritten with null or a default value. Use PUT when the client always sends the full updated resource.

@Put(':id')
replace(
  @Param('id', ParseIntPipe) id: number,
  @Body() updateProductDto: UpdateProductDto,
) {
  return this.productsService.replace(id, updateProductDto);
}

PATCH — Partial Update

PATCH requests update only the fields that the client sends. If a product has a name, price, and stock, and the client only sends a new price, PATCH updates only the price. The name and stock stay unchanged.

@Patch(':id')
update(
  @Param('id', ParseIntPipe) id: number,
  @Body() patchProductDto: PatchProductDto,
) {
  return this.productsService.update(id, patchProductDto);
}

PUT vs PATCH — A Clear Diagram

Existing Record:
  { name: 'Laptop', price: 999, stock: 50 }

PUT /products/1 body: { name: 'Laptop Pro', price: 1099, stock: 50 }
  Result: { name: 'Laptop Pro', price: 1099, stock: 50 }
  → Must send ALL fields, even unchanged ones

PATCH /products/1 body: { price: 1099 }
  Result: { name: 'Laptop', price: 1099, stock: 50 }
  → Only the price changes; other fields stay intact

DELETE — Removing Data

DELETE requests remove a resource. Most APIs return either a success message (200) or no body at all (204):

@Delete(':id')
@HttpCode(204)
remove(@Param('id', ParseIntPipe) id: number) {
  return this.productsService.remove(id);
}

HEAD and OPTIONS

HEAD behaves exactly like GET but returns only headers — no response body. Clients use it to check whether a resource exists or to read metadata without downloading content. OPTIONS tells clients which HTTP methods a particular URL supports. NestJS handles both through their respective decorators:

@Head(':id')
check(@Param('id') id: string) {
  // No body returned, just headers
}

@Options()
options() {
  // Returns allowed methods
}

The @All Decorator

The @All() decorator matches any HTTP method for a route. Use it as a fallback or for endpoints that deliberately handle multiple method types:

@All('catch-all')
handleAll(@Req() req: Request) {
  return `Method ${req.method} hit this route`;
}

RESTful Route Design with HTTP Methods

Combining HTTP methods with meaningful URLs creates a RESTful API. A well-designed products API follows this pattern:

GET    /products          → Get all products
GET    /products/:id      → Get one product
POST   /products          → Create a product
PUT    /products/:id      → Replace a product
PATCH  /products/:id      → Partially update a product
DELETE /products/:id      → Delete a product

This pattern is intuitive, consistent, and understood by every developer who works with REST APIs. NestJS makes it straightforward to implement this entire structure in one controller class using the appropriate decorator for each method.

Idempotency

GET, PUT, DELETE, HEAD, and OPTIONS are idempotent — calling them multiple times produces the same result. Sending DELETE /products/5 five times deletes product 5 once; the subsequent calls either do nothing or return a not-found error. POST is not idempotent — sending the same POST request twice creates two records. Understanding idempotency helps you design APIs that behave predictably when network issues cause clients to retry requests.

Leave a Comment

Your email address will not be published. Required fields are marked *