📜  PUT vs POST (1)

📅  最后修改于: 2023-12-03 14:45:42.341000             🧑  作者: Mango

PUT vs POST

HTTP protocol supports several request methods, and two of the most commonly used are PUT and POST. Although they perform similar functions, they have some key differences that programmers should be aware of.

PUT

PUT method is used to update an existing resource on a server. When a client wants to update an existing resource, it sends a PUT request to the server. The body of the request message contains the updated representation of the resource. If the resource does not exist on the server, a new resource will be created.

Examples
PUT /api/users/123 HTTP/1.1
Host: example.com
Content-Type: application/json

{
    "name": "John Smith",
    "email": "john.smith@example.com",
    "age": 30
}

In the above example, a PUT request is sent to the server to update user with id 123. The new data for the user is sent in the request body as a JSON object.

POST

POST method is used to send data to the server to create a new resource. When a client wants to create a new resource on the server, it sends a POST request to the server. The body of the request message contains the data to be sent. The server processes the data and creates a new resource.

Examples
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json

{
    "name": "John Smith",
    "email": "john.smith@example.com",
    "age": 30
}

In the above example, a POST request is sent to the server to create a new user. The new user data is sent in the request body as a JSON object.

Differences between PUT and POST

PUT and POST methods have some key differences that programmers should be aware of:

  • PUT is idempotent, meaning that if the same request is sent multiple times, the result will be the same every time. POST is not idempotent and can result in multiple resources being created if the same request is sent multiple times.
  • PUT is used to update an existing resource while POST is used to create a new resource.
  • PUT requests should contain the full representation of the resource, while POST requests only need to contain the data to be processed by the server.
Conclusion

Both PUT and POST methods are used to send data to the server, but they have different use cases. PUT is used to update an existing resource while POST is used to create a new resource. Programmers should choose the appropriate method for their application requirements.