- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 367字
- 2021-06-24 17:04:22
POST, PUT, and PATCH
The POST method is used to create a resource on the server. In the previous books API, this operation creates a new book with the given details. A successful POST operation returns a 2xx status code. The POST request can update multiple resources: /v1/books.
The POST request can have a JSON body like the following:
{"name" : "Lord of the rings", "year": 1954, "author" : "J. R. R. Tolkien"}
This actually creates a new book in the database. An ID is assigned to this record so that when we GET the resource, the URL is created. So, POST should be done only once, in the beginning. In fact, Lord of the Rings was published in 1955. So, we entered the published date incorrectly. In order to update the resource, let's use the PUT request.
The PUT method is similar to POST. It is used to replace the resource that already exists. The main difference is that PUT is an idempotent operation. A POST call creates two instances with the same data. But PUT updates a single resource that already exists:
/v1/books/1256
PUT does this using a body containing JSON syntax, as follows:
{"name" : "Lord of the rings", "year": 1955, "author" : "J. R. R. Tolkien"}
1256 is the ID of the book. It updates the preceding book with year:1955. Did you observe the drawback of PUT? It actually replaced the entire old record with the new one. We needed to change a single column. But PUT replaced the whole record. That is bad. For this reason, the PATCH request was introduced.
The PATCH method is similar to PUT, except it won't replace the whole record. PATCH, as the name suggests, patches the column that is being modified. Let's update the book 1256 with a new column called ISBN:
/v1/books/1256
Let's use put the following JSON in the body:
{"isbn" : "0618640150"}
It tells the server, "search for the book with ID 1256. Then add/modify this column with the given value."
- Learning Scala Programming
- Boost程序庫完全開發指南:深入C++”準”標準庫(第5版)
- Java 9 Concurrency Cookbook(Second Edition)
- UI智能化與前端智能化:工程技術、實現方法與編程思想
- Web Application Development with MEAN
- PostgreSQL Replication(Second Edition)
- Spring Boot Cookbook
- Mastering Unity 2D Game Development(Second Edition)
- Fast Data Processing with Spark(Second Edition)
- 從零開始:UI圖標設計與制作(第3版)
- Practical GIS
- Drupal 8 Development:Beginner's Guide(Second Edition)
- After Effects CC案例設計與經典插件(視頻教學版)
- HTML5與CSS3權威指南
- Node.js實戰:分布式系統中的后端服務開發