HTTP Methods

HTTP methods are like "action commands" for your data.

In RESTful APIs, we mainly use four methods, corresponding to four basic operations on data:

HTTP Method Purpose Corresponding Operation Life Analogy
GET Retrieve Data Read View Menu
POST Create Data Create Order Dishes
PUT Update Data Update Modify Order
DELETE Delete Data Delete Cancel Order

GET Method

GET is used to retrieve data, just like asking the waiter, "What dishes do you have today?"

// 获取所有用户
GET /api/users

// 获取特定用户
GET /api/users/123

// 获取用户的订单
GET /api/users/123/orders

Features:

  • Safe operation, does not modify data
  • Can be cached
  • Parameters are placed in the URL

POST Method

POST is used to create new data, just like telling the waiter, "I'd like to order a Kung Pao Chicken"

// 创建新用户
POST /api/users
{
  "name": "张三",
  "email": "[email protected]"
}

// 创建新订单
POST /api/orders
{
  "userId": 123,
  "items": ["商品A", "商品B"]
}

Features:

  • Modifies server state
  • Not idempotent (multiple calls will create multiple resources)
  • Data is placed in the request body

PUT Method

PUT is used to update the entire resource, just like saying, "Change my order to this"

// 更新用户信息
PUT /api/users/123
{
  "name": "李四",
  "email": "[email protected]",
  "phone": "13800138000"
}

Features:

  • Is idempotent (multiple calls produce the same result)
  • Usually replaces the entire resource
  • If the resource does not exist, it may create a new resource

DELETE Method

DELETE is used to delete a resource, just like saying, "Cancel my order"

// 删除用户
DELETE /api/users/123

// 删除订单
DELETE /api/orders/456
  • Is idempotent
  • Deletes the specified resource
  • After success, the resource no longer exists

HTTP Status Codes

After the server processes the request, it returns a status code to tell you the result:

Status Code Meaning Description
200 OK Request succeeded
201 Created Resource created successfully
400 Bad Request Bad request
401 Unauthorized Unauthorized
404 Not Found Resource not found
500 Internal Server Error Internal server error
Other extensions