- Building RESTful Web services with Go
- Naren Yellavula
- 356字
- 2021-07-02 20:14:02
POST, PUT, and PATCH
The POST method is used to create a resource on the server. In the previous book's API, this operation creates a new book with the given details. A successful POST operation returns a 201 status code. The POST request can update multiple resources: /v1/books.
The POST request has a body like this:
{"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 us 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 idempotent. A POST call creates two instances with the same data. But PUT updates a single resource that already exists:
/v1/books/1256
with body that is JSON like this:
{"name" : "Lord of the rings", "year": 1955, "author" : "J. R. R. Tolkien"}
1256 is the ID of the book. It updates the preceding book by 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 us update the book 1256 with a new column called ISBN:
/v1/books/1256
with the JSON body like this:
{"isbn" : "0618640150"}
It tells the server, Search for the book with id 1256. Then add/modify this column with the given value.
PUT and PATCH both return the 200 status for success and 404 for not found.
- Web安全防護(hù)指南:基礎(chǔ)篇
- Truffle Quick Start Guide
- 射頻通信系統(tǒng)
- 雷達(dá)饋線技術(shù)
- 智慧光網(wǎng)絡(luò):關(guān)鍵技術(shù)、應(yīng)用實(shí)踐和未來演進(jìn)
- SAE原理與網(wǎng)絡(luò)規(guī)劃
- Android UI Design
- 物聯(lián)網(wǎng)基礎(chǔ)及應(yīng)用
- Laravel Application Development Cookbook
- 物聯(lián)網(wǎng)M2M開發(fā)技術(shù):基于無線CPU-Q26XX
- 5G智慧交通
- Cisco無線局域網(wǎng)配置基礎(chǔ)
- 物聯(lián)網(wǎng)技術(shù)與實(shí)踐
- 互聯(lián)網(wǎng)安全的40個(gè)智慧洞見(2018)
- Hands-On Cloud:Native Microservices with Jakarta EE