Created: 2024/01/03

Updated: 2024/01/03

Understanding REST API Methods: GET, POST, PATCH, PUT, and DELETE with Express.js & TypeScript Examples

Understanding REST API Methods: GET, POST, PATCH, PUT, and DELETE with Express.js & TypeScript Examples post image cover

Author ✍️

Versatile Node.js developer with a knack for turning ideas into robust enterprise solutions. Proficient in the entire development lifecycle, I bring expertise in crafting scalable and efficient applications.

Understand the key differences between GET, POST, PATCH, PUT, and DELETE HTTP methods in REST APIs with practical Express.js and TypeScript examples.

In the world of web development, REST APIs play a pivotal role in facilitating client-server communication. A RESTful API operates by handling requests and responses via HTTP methods that are designed to perform specific actions. The most common methods are GET, POST, PATCH, PUT, and DELETE. Understanding when and how to use each of these methods is essential for developing robust and efficient APIs. In this blog post, we'll explore the differences between these methods with examples using Express.js and TypeScript.

GET Method

🔗

The GET method is used to retrieve data from the server. It is a read-only operation, meaning that using GET should not change the state of the resource on the server. An API that adheres to REST principles will use GET requests to fetch resources without causing any side effects.

GET Example with Express.js and TypeScript:

🔗
import express from "express"; import { Request, Response } from "express"; const app = express(); // Define a route to fetch a list of items app.get("/items", (req: Request, res: Response) => { // Simulate fetching items from a database const items = [ { id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }, ]; res.json(items); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

POST Method

🔗

POST is used to send data to the server to create a new resource. It's a write operation that can potentially change the state of the application by adding a new record or performing another action that modifies data.

POST Example with Express.js and TypeScript:

🔗
import express, { json } from "express"; import { Request, Response } from "express"; const app = express(); app.use(json()); // Define a route to create a new item app.post("/items", (req: Request, res: Response) => { // Simulate creating a new item with the request body data const newItem = req.body; // Simulate adding the new item to the database and returning the item with a new id const createdItem = { ...newItem, id: Date.now() }; res.status(201).json(createdItem); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

PATCH Method

🔗

PATCH is utilized when you want to apply partial modifications to a resource. Unlike PUT, PATCH updates only the specified fields of a resource, rather than replacing the whole resource.

PATCH Example with Express.js and TypeScript:

🔗
import express, { json } from "express"; import { Request, Response } from "express"; const app = express(); app.use(json()); // Define a route to partially update an item app.patch("/items/:id", (req: Request, res: Response) => { // Extract the item ID from the URL parameters and the update data from the request body const { id } = req.params; const updateData = req.body; // Simulate fetching the item from the database and updating specific fields let item = { id: parseInt(id), name: "Item 1" }; // Simulated existing item item = { ...item, ...updateData }; res.json(item); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

PUT Method

🔗

PUT requests are used to send data to the server to update a resource or create a new resource if it does not already exist. A key aspect of PUT is that it is idempotent, meaning that making multiple identical requests will have the same effect as making a single request.

PUT Example with Express.js and TypeScript:

🔗
import express, { json } from "express"; import { Request, Response } from "express"; const app = express(); app.use(json()); // Define a route to update an entire item app.put("/items/:id", (req: Request, res: Response) => { // The entire item is replaced with the request body data const { id } = req.params; const updatedItem = { id: parseInt(id), ...req.body }; // Simulate replacing the item in the database res.json(updatedItem); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

DELETE Method

🔗

DELETE is employed to remove a resource from the server. It is a destructive operation that, if successful, should result in the resource being permanently deleted.

DELETE Example with Express.js and TypeScript:

🔗
import express from "express"; import { Request, Response } from "express"; const app = express(); // Define a route to delete an item app.delete("/items/:id", (req: Request, res: Response) => { const { id } = req.params; // Simulate deleting the item from the database console.log(`Deleting item with id: ${id}`); // Send a response to indicate success res.status(204).send(); }); const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });

When to Use Each Method

🔗
  • Use GET to fetch data without modifying any resources.
  • Use POST to create new resources on the server.
  • Use PATCH to make partial updates to existing resources.
  • Use PUT when you want to update a resource entirely or create it if it does not exist.
  • Use DELETE to remove resources from the server.

In conclusion, choosing the right HTTP method for the task at hand is critical for RESTful API design. By following the principles of each method and knowing when to use them, you can ensure that your API is intuitive and conducive to maintainable, scalable architecture. Our examples using Express.js and TypeScript should give you a strong foundation to experiment and build your own RESTful services.

You may also like

🔗