What is the most common/industry standard response code for HTTP PUT when:
Client made a well-formed request and
The content of the file/message/data is empty and
Because of that nothing has been changed on the server/in the database
In my specific case the client sends HTTP PUT with an empty JSON like this:
{}
while I expect something more like this:
{
key1: {
something: value,
something2:value2
},
key2: {
something: value3,
something: value4
}
}
which in my case would translate to 4 new rows being upserted to the database.
I am considering either 400 (because maybe it is a bad request when you call a HTTP PUT but you don't have anything to put there), 200, 204 and 304.
My question is different from this and this because they are about HTTP GET method, and is different from this because while it is about HTTP PUT the answer doesn't address my case.
A PUT request should replace what was on the server at the specified uri.
So if the resource at the uri already was empty, and the new resource that's being put is also empty, nothing changed but it's still a success, so 200 OK is fine.
If the resource didn't exist and you create a new 0-byte resource, 201 Created might be more appropriate.
If the resource did exist but it was not empty, and you send an empty PUT request, it should replace the existing resource with an empty one.
This is where you are going wrong, because PUT should not be used for a per-record "upsert" like you are doing.
If the PUT request you state was semantically correct, it should wipe out all existing records tied to that location.
What you probably want is PATCH or POST.
Related
I have learned you can "decorate" the HTTP transport so that you can details of the request, however I can't quite figure out how you log the URL in the same line.
https://play.golang.org/p/g-ypQN9ceGa
results in
INFO[0000] Client request dns_start_ms=0 first_byte_ms=590 response_code=200 total_ms=590 url=
INFO[0000] 200
I'm perpetually confused if I should be using https://golang.org/pkg/context/#WithValue to pass around the context in a struct, especially in light where https://blog.golang.org/context-and-structs concludes with pass context.Context in as an argument.
Go through the behaviour of how the request is constructed in request.go from net/http. You see that the RequestURI field is never set there. Quoting from same reference,
Usually the URL field should be used instead.
It is an error to set this field in an HTTP client request
So, I would suggest you to use request.URL instead.
It is a parsed from the request uri. It should have the data you need.
You can construct the output as following:
f := log.Fields{
"url": fmt.Sprintf("%s %s%s", r.Method, r.URL.Host, r.URL.Path),
}
Also, in my experience, it is far more easier to use context.WithValue and pass the context as an argument.
Replace r.RequestURI by r.URL.String() in your code to log the full, valid URL (https://golang.org/pkg/net/url/#URL.String). RequestURI is empty on the client side (https://golang.org/pkg/net/http/#Request), as the output from your code is showing.
I don't see how context.Context relates to your question, but I believe https://blog.golang.org/context-and-structs is considered "best practice".
I need to reuse value which is generated for my previous request.
For example, at first request, I make a POST to the URL /api/products/{UUID} and get HTTP response with code 201 (Created) with an empty body.
And at second request I want to get that product by request GET /api/products/{UUID}, where UUID should be from the first request.
So, the question is how to store that UUID between requests and reuse it?
You can use the Request Sent Dynamic values https://paw.cloud/extensions?extension_type=dynamic_value&q=request+send these will get the value used last time you sent a requst for a given request.
In your case you will want to combine the URLSentValue with the RegExMatch (https://paw.cloud/extensions/RegExMatch) to first get the url as it was last sent for a request and then extract the UUID from the url.
e.g
REQUEST A)
REQUEST B)
The problem is in your first requests answer. Just dont return "[...] an empty body."
If you are talking about a REST design, you will return the UUID in the first request and the client will use it in his second call: GET /api/products/{UUID}
The basic idea behind REST is, that the server doesn't store any informations about previous requests and is "stateless".
I would also adjust your first query. In general the server should generate the UUID and return it (maybe you have reasons to break that, then please excuse me). Your server has (at least sometimes) a better random generator and you can avoid conflicts. So you would usually design it like this:
CLIENT: POST /api/products/ -> Server returns: 201 {product_id: UUID(1234...)}
Client: GET /api/products/{UUID} -> Server returns: 200 {product_detail1: ..., product_detail2: ...}
If your client "loses" the informations and you want him to be later able to get his products, you would usually implement an API endpoint like this:
Client: GET /api/products/ -> Server returns: 200 [{id:UUID(1234...), title:...}, {id:UUID(5678...),, title:...}]
Given something like this, presuming the {UUID} is your replacement "variable":
It is probably so simple it escaped you. All you need to do is create a text file, say UUID.txt:
(with sample data say "12345678U910" as text in the file)
Then all you need to do is replace the {UUID} in the URL with a dynamic token for a file. Delete the {UUID} portion, then right click in the URL line where it was and select
Add Dynamic Value -> File -> File Content :
You will get a drag-n-drop reception widget:
Either press the "Choose File..." or drop the file into the receiver widget:
Don't worry that the dynamic variable token (blue thing in URL) doesn't change yet... Then click elsewhere to let the drop receiver go away and you will have exactly what you want, a variable you can use across URLs or anywhere else for that matter (header fields, form fields, body, etc):
Paw is a great tool that goes asymptotic to awesome when you explore the dynamic value capability. The most powerful yet I have found is the regular expression parsing that can parse raw reply HTML and capture anything you want for the next request... For example, if you UUID came from some user input and was ingested into the server, then returned in a html reply, you could capture that from the reply HTML and re-inject it to the URL, or any field or even add it to the cookies using the Dynamic Value capabilities of Paw.
#chickahoona's answer touches on the more normal way of doing it, with the first request posting to an endpoint without a UUID and the server returning it. With that in place then you can use the RegExpMatch extension to extract the value from the servers's response and use it in subsequent requests.
Alternately, if you must generate the UUID on the client side, then again the RegExpMatch extension can help, simply choose the create request's url for the source and provide a regexp that will strip the UUID off the end of it, such as /([^/]+)$.
A third option I'll throw out to you, put the UUID in an environment variable and just have all of your requests reference it from there.
What is the difference between PUT, POST and PATCH methods in HTTP protocol?
Difference between PUT, POST, GET, DELETE and PATCH in HTTP Verbs:
The most commonly used HTTP verbs POST, GET, PUT, DELETE are similar to CRUD (Create, Read, Update and Delete) operations in database. We specify these HTTP verbs in the capital case. So, the below is the comparison between them.
Create - POST
Read - GET
Update - PUT
Delete - DELETE
PATCH: Submits a partial modification to a resource. If you only need to update one field for the resource, you may want to use the PATCH method.
Note:
Since POST, PUT, DELETE modifies the content, the tests with Fiddler for the below url just mimicks the updations. It doesn't delete or modify actually. We can just see the status codes to check whether insertions, updations, deletions occur.
URL: http://jsonplaceholder.typicode.com/posts/
GET:
GET is the simplest type of HTTP request method; the one that browsers use each time you click a link or type a URL into the address bar. It instructs the server to transmit the data identified by the URL to the client. Data should never be modified on the server side as a result of a GET request. In this sense, a GET request is read-only.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: GET
url: http://jsonplaceholder.typicode.com/posts/
Response: You will get the response as:
"userId": 1, "id": 1, "title": "sunt aut...", "body": "quia et suscipit..."
In the “happy” (or non-error) path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
2) POST:
The POST verb is mostly utilized to create new resources. In particular, it's used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.
On successful creation, return HTTP status 201, returning a Location header with a link to the newly-created resource with the 201 HTTP status.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: POST
url: http://jsonplaceholder.typicode.com/posts/
Request Body:
data: {
title: 'foo',
body: 'bar',
userId: 1000,
Id : 1000
}
Response: You would receive the response code as 201.
If we want to check the inserted record with Id = 1000 change the verb to Get and use the same url and click Execute.
As said earlier, the above url only allows reads (GET), we cannot read the updated data in real.
3) PUT:
PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: PUT
url: http://jsonplaceholder.typicode.com/posts/1
Request Body:
data: {
title: 'foo',
body: 'bar',
userId: 1,
Id : 1
}
Response: On successful update it returns status 200 (or 204 if not returning any content in the body) from a PUT.
4) DELETE:
DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.
On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.
Checking with Fiddler or PostMan:
We can use Fiddler for checking the response. Open Fiddler and select the Compose tab.
Specify the verb and url as shown below and click Execute to check the response.
Verb: DELETE
url: http://jsonplaceholder.typicode.com/posts/1
Response: On successful deletion it returns HTTP status 200 (OK) along with a response body.
Example between PUT and PATCH
PUT
If I had to change my first name then send PUT request for Update:
{ "first": "Nazmul", "last": "hasan" }
So, here in order to update the first name we need to send all the parameters of the data again.
PATCH:
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data.
Ex: if we need to update only the first name, we pass only the first name.
Please refer the below links for more information:
https://jsonplaceholder.typicode.com/
https://github.com/typicode/jsonplaceholder#how-to
What is the main difference between PATCH and PUT request?
http://www.restapitutorial.com/lessons/httpmethods.html
The below definition is from the real world example.
Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to the client for reference.
POST
If the client sends data without any identifier, then we will store the data and assign/generate a new identifier.
If the client again sends the same data without any identifier, then we will store the data and assign/generate a new identifier.
Note: Duplication is allowed here.
PUT
If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will create a resource with the data and assign/generate a new identifier.
PATCH
If the client sends data with an identifier, then we will check whether that identifier exists. If the identifier exists, we will update the resource with the data, else we will throw an exception.
Note: On the PUT method, we are not throwing an exception if an identifier is not found. But in the PATCH method, we are throwing an exception if the identifier is not found.
Do let me know if you have any queries on the above.
Here is a simple description of all:
POST is always for creating a resource ( does not matter if it was duplicated )
PUT is for checking if resource exists then update, else create new resource
PATCH is always for updating a resource
PUT = replace the ENTIRE RESOURCE with the new representation provided
PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)
https://laracasts.com/discuss/channels/general-discussion/whats-the-differences-between-put-and-patch?page=1
Simplest Explanation:
POST - Create NEW record
PUT - If the record exists, update else, create a new record
PATCH - update
GET - read
DELETE - delete
Think of it this way...
POST - create
PUT - replace
PATCH - update
GET - read
DELETE - delete
Request Types
create - POST
read - GET
create or update - PUT
delete - DELETE
update - PATCH
GET/PUT is idempotent
PATCH can be sometimes idempotent
What is idempotent -
It means if we fire the query multiple times it should not afftect the result of it.(same output.Suppose a cow is pregnant and if we breed it again then it cannot be pregnent multiple times)
get :-
simple get. Get the data from server and show it to user
{
id:1
name:parth
email:x#x.com
}
post :-
create new resource at Database. It means it adds new data. Its not idempotent.
put :-
Create new resource otherwise add to existing.
Idempotent because it will update the same resource everytime and output will be the same.
ex.
- initial data
{
id:1
name:parth
email:x#x.com
}
perform put-localhost/1
put email:ppp#ppp.com
{
id:1
email:ppp#ppp.com
}
patch
so now came patch request
PATCH can be sometimes idempotent
id:1
name:parth
email:x#x.com
}
patch name:w
{
id:1
name:w
email:x#x.com
}
HTTP Method
GET yes
POST no
PUT yes
PATCH no*
OPTIONS yes
HEAD yes
DELETE yes
Resources :
Idempotent -- What is Idempotency?
Main Difference Between PUT and PATCH Requests:
Suppose we have a resource that holds the first name and last name of a person.
If we want to change the first name then we send a put request for Update
{ "first": "Michael", "last": "Angelo" }
Here, although we are only changing the first name, with PUT request we have to send both parameters first and last.
In other words, it is mandatory to send all values again, the full payload.
When we send a PATCH request, however, we only send the data which we want to update. In other words, we only send the first name to update, no need to send the last name.
Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below
Sometimes POST is considered as for updates w.r.t PUT for create
Does HTTP mandates/checks for sending full vs partial data in PATCH? Otherwise, PATCH may be quite same as update as in PUT/POST
You may understand the restful HTTP methods as corresponding operations on the array in javascript (with index offset by 1).
See below examples:
Method
Url
Meaning
GET
/users
return users array
GET
/users/1
return users[1] object
POST
/users
users.push(body); return last id or index
PUT
/users
replace users array
PUT
/users/1
users[1] = body
PATCH
/users/1
users[1] = {...users[1], ...body }
DELETE
/users/1
delete users[1]
Reference to RFC: https://www.rfc-editor.org/rfc/rfc9110.html#name-method-definitions
POST - creates new object
PUT - updates old object or creates new one if not exist
PATCH - updates/modify old object. Primarly intended for for modificaiton.
There is few interpritation of RFC like mentioned before, but if you read carefully then you can notice that PUT and PATCH methods came after POST witch is common old fashion way to create native HTML Forms.
Therefore if you try to support all methods (like PATCH or DELETE), it can be suggested that the most approapreate way to use all methods is to stick to CRUD model:
Create - PUT
Read - GET
Update - PATCH
Delete - DELETE
Old HTML native way:
Read - GET
Create/Update/Delete - POST
Good Luck Coders! ;-)
Let's say you want to get list of users by calling GET to api/users, but currently the table was truncated so there are no users. What is the proper response for this scenario: 404 or 204?
I'd say, neither.
Why not 404 (Not Found) ?
The 404 status code should be reserved for situations, in which a resource is not found. In this case, your resource is a collection of users. This collection exists but it's currently empty. Personally, I'd be very confused as an author of a client for your application if I got a 200 one day and a 404 the next day just because someone happened to remove a couple of users. What am I supposed to do? Is my URL wrong? Did someone change the API and neglect to leave a redirection.
Why not 204 (No Content) ?
Here's an excerpt from the description of the 204 status code by w3c
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.
While this may seem reasonable in this case, I think it would also confuse clients. A 204 is supposed to indicate that some operation was executed successfully and no data needs to be returned. This is perfect as a response to a DELETE request or perhaps firing some script that does not need to return data. In case of api/users, you usually expect to receive a representation of your collection of users. Sending a response body one time and not sending it the other time is inconsistent and potentially misleading.
Why I'd use a 200 (OK)
For reasons mentioned above (consistency), I would return a representation of an empty collection. Let's assume you're using XML. A normal response body for a non-empty collection of users could look like this:
<users>
<user>
<id>1</id>
<name>Tom</name>
</user>
<user>
<id>2</id>
<name>IMB</name>
</user>
</users>
and if the list is empty, you could just respond with something like this (while still using a 200):
<users/>
Either way, a client receives a response body that follows a certain, well-known format. There's no unnecessary confusion and status code checking. Also, no status code definition is violated. Everybody's happy.
You can do the same with JSON or HTML or whatever format you're using.
I'd answer one of two codes depending on runtime situation:
404 (Not Found)
This answer is pretty correct if you have no table. Not just empty table but NO USER TABLE. It confirms exact idea - no resource. Further options are to provide more details WHY your table is absent, there is couple of more detailed codes but 404 is pretty good to refer to situation where you really have no table.
200 (OK)
All cases where you have table but it is empty or your request processor filtered out all results. This means 'your request is correct, everything is OK but you do not match any data just because either we have no data or we have no data which matches your request. This should be different from security denial answer. I also vote to return 200 in situation where you have some data and in general you are allowed to access table but have no access to all data which match your request (data was filtered out because of object level security but in general you are allowed to request).
If you are expecting list of user object, the best solution is returning an empty list ([]) with 200 OK than using a 404 or a 204 response.
definitely returns 200.
404 means resource not found. But the resource exists. And also, if the response has 404 status. How can you know users list empty or filled?
'/users' if is empty should return '200'.
'/users/1' if the id is not found. should return 404.
It must 200 OK with empty list.
Why: Empty table means the table exists but does not have any records.
404 Not Found means requested end point does not exist.
We're currently working to the OData standard:
http://www.odata.org/developers/protocols/operations
According to this standard, if you perform an PUT operation against your data, you should return a 204 status code. The standard says that:
When processing a PUT request servers return status 204 (No Content)
to indicate success, no response body is needed.
Now, according to what one reads elsewhere, some places claim that if you're returning a 204 you should absolutely NOT return a response body - it's not a question of whether one is needed or not.
The problem is we kind of need to return a body. In this case we're performing an update query on a batch of items and partial success (i.e. some are updated, some are not) is possible. We'd like to inform the client of what the failures were and the response body is the only way of doing it that I can think of.
So what's the "correct" way of doing this. Should I flout the W3C and return a body? Or should I flout OData and return a different response code? Or is there another possibility?
The 204 response to PUT is not a mandatory requirement for OData servers (note that the odata.org is not a normative reference, the MS-OData document is). You can return 200 with body, in which case the body you return should be a serialization of the updated entity (after the updates were applied by the server). In fact in OData V3 we now have a support for Prefer header which does exactly this. The client can include a Prefer header with the PUT request and ask the server to respond with 200 and the updated entityt.
I think you must not return content and should consider returning a header to indicate the partially complete command.
The spec states
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
You may also wish to take the batch approach, http://www.odata.org/developers/protocols/batch
You shouldn't return 204 unless the operation succeeded completely.
Seems weird to return a 204 for a PUT. I always thought 204 paired with the DELETE. Where the text 'no content' means that the resource is no longer on the server. The PUT doesn't have anything to do with removing resources so shouldn't use 204. Also 204 is a success code so should be used when 100% successful.