I have an order resource on server. the url looks like http://example.net/order/1
the get method on above url will return whole order object like
{
"orderNo": "1",
"status": "order place",
"orderTimestamp": "2018-11-22 14:28:12",
"invoiceAddress": {
"salutation": "M",
"firstName": "Dieter",
"lastName": "Wolf",
"companyName": "",
"street": "Michaelkirchstr.",
"houseNo": "16",
"zipCode": "31604",
"city": "Raddestorf",
"countryIsoCode": "DEU",
"phone": "05763 82 60 80",
"email": "DieterWolf#armyspy.com"
},
"deliveryAddress": {}
"items": [
{
...
}
],
"returnItemsDetails": []
}
Now I wish to offer patch method on same api so one can update/add few details like delivery address. To update order detail one may request following request with patch http method on same order url
{
"deliveryAddress": {
"deliveryType": "CUSTOMER",
"salutation": "M",
"firstName": "Dieter",
"lastName": "Wolf",
"companyName": "",
"street": "Michaelkirchstr.",
"houseNo": "16",
"zipCode": "31604 ",
"city": "Raddestorf",
"countryIsoCode": "DEU",
"phone": "05763 82 60 80",
"email": "DieterWolf#armyspy.com"
}
}
My question is what should be there in response of patch request according to REST standard? or Is there any document where I can find about response data and format for REST api.
My question is what should be there in response of patch request according to REST standard? or Is there any document where I can find about response data and format for REST api.
According to RFC 5789 a successful response can return any success codes (i.e. 200 or 204). It should ideally also contain an ETag header to allow clients to track the current version for eventual consecutive requests (which is basically used for optimistic locking on the resources state).
The spec presents a 204 No Content sample as a patch consists, loosely speaking, of a set of instructions calculated by the client that a server should apply to transform the target resource to the desired state. So the client knows beforehand how the final result should look like and the server thus does not need to inform the client about it.
In case you want to return a 200 OK response I suggest returning a representation suggested by the Accept request header issued by the client (Content-Type negotiation) in order to avoid to force a client some predefined media type format it might not understand or reason further possibilities from.
If you need to apply unpredictable changes to a resource, i.e. based on some calculations done on the server side or include the payload to a certain predefined element (as probably done in your sample), RFC 5789 explicitly states that POST should be used instead of PUT or PATCH. Further note, that you could support application/merge-patch+json media format and its semantics defined in RFC 7386 to issue such a (sample) body as payload to a PATCH request and probably achieve your desired outcome, though.
My question is what should be there in response of patch request according to REST standard? or Is there any document where I can find about response data and format for REST api.
Patch is defined in RFC 5789. Section 2 demonstrates that one possibility is that you will return an updated representation of the resource:
A response to this method is only cacheable if it contains explicit freshness information (such as an Expires header or "Cache-Control: max-age" directive) as well as the Content-Location header matching the Request-URI, indicating that the PATCH response body is a resource representation.
But I wasn't able to find a specification for the more general case. So what I would suggest is that one interpret the specifications from RFC 7231 for PUT and DELETE also be applied to PATCH
a representation of the status of the action
Related
I want to route all requests for a given resource to the same server. If a resource is created on a server, all following requests should be routed to the same server.
To be sticky on the url is not the problem, but how can I fill the stick-table from the first response?
Example:
Request:
POST /resources
{
"value": "bla"
}
Response:
{
"id": "1234",
"value": "bla"
}
GET /resources/1234
{
"id": "1234",
"value": "bla"
}
The second request should be routed to the same server, that handled the first request. Is there a way to get this done with haproxy?
Finally found a solution that works. I am posting this, in case somebody else is interested in the solution. The relevant lines are the following in section backend:
acl recources_path capture.req.uri,field(1,?) /resources
stick-table type string len 10 size 5M
stick match capture.req.uri,field(3,/)
# trying to parse the id out of the post response
stick store-response res.payload(0,0),field(2,{),field(4,\") if METH_POST recources_path
Especially the parsing of the response body seems to be not the intended way to use haproxy. Adding a response header with the resource id makes it much easier to handle the situation.
I think this is a classic and typical question but I didn't find its answer.
In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL.
But what I didn't understand is how the same api may have different behavior by just changing the method.
Here is an example. I use SoapUI 5.5.0, this is the link of the api: https://reqres.in/api/users/1
when I use GET method I get this:
{
"data": {
"id": 1,
"email": "george.bluth#reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
}
}
and by changing only the method to POST, I get this:
{
"id": "244",
"createdAt": "2020-02-27T14:30:32.100Z"
}
(the id and date changes each time)
as described in this link https://reqres.in/ that it is creating an instance and we can add parameters..
BUT, can any one explain how is it technically possible to have different behavior with different methods on the same URL.
In my knowledge, the POST method is used to send data to the server with request parameter in message body to make it secure. And GET method is to retrieve data with parameters in the URL.
That's probably getting in your way.
HTTP Requests are messages; each message starts with a request-line
method SP request-target SP HTTP-version CRLF
The request-target identifies the target resource upon which to apply the request
The method token indicates the request method to be performed on the target resource.
You can think of it being like a function call
GET(target-resource)
POST(target-resource, message-body)
Or equivalently you can think of the resources as objects that share an understanding of message semantics
target-resource.GET()
target-resource.POST(message-body)
But what I didn't understand is how the same api may have different behavior by just changing the method.
The same way that an api can exhibit different behavior by just changing the request-target.
In HTTP, the request-line is literally human readable text that the server will parse. Having parsed the request-line, the server program can then branch to whatever code it wants to use to do the work, based on the values it found in the message.
In many frameworks (Spring, Rails) the branching logic is provided by the framework code; your bespoke handlers only need to be correctly registered and the framework ensures that each request is forwarded to the correct handler.
how is it technically possible to have different behavior with
different methods on the same URL
for the technical possibility, you can look at the spring framework's answer to this.
You can have a controller that is accessible on a single url but can contacted in four says, GET, PUT, POST, DELETE. To do this, Spring provides the annotations #GetMapping, #PostMapping, #PutMapping, #DeleteMapping.
All the requests are sent to the same url and Spring works out which method to call based on the verb.
In Restful APIs, verbs have very important meaning.
GET: Retrieve data
POST: Create a new entity with the request's body
PUT: Replace an entity with the request's body
PATCH: Update some properties of an entity with the request's body. A.K.A. Partial update
In your case, changing the verb from get to post has the effect of creating a new entity with ID 1. That's why you get a response with the newly created ID and a createdAt timestamp.
I have a resource class. I need two APIs :
bulk create classes
create one class.
In the REST standards should I create 2 APIs:
/classes/bulk/ --- for bulk create
/classes/ --- to create one class.
This approach doesn't seem to REStFul to me or is it?
Is it more RESTful to use query param for this : /classes?type=bulk ?
Also, the processing logic and the response schema for 200 is different for the bulk and the non bulk call
This approach doesn't seem to RESTful to me or is it?
The URI spelling is not relevant in the REST architectural. Appending /bulk to the URI or not won't make your application more RESTful or not.
Alternatively to use /bulk in the URI, you could use the same URI for handling the creation of one or multiple resources. Consider that your resource is a message. Then you could have the following:
POST /api/messages HTTP/1.1
Host: example.org
Content-Type: application/json
{
"to": "John"
"content": "Hi"
}
POST /api/messages HTTP/1.1
Host: example.org
Content-Type: application/json
[
{
"to": "John"
"content": "Hi"
},
{
"to": "James"
"content": "Hey"
},
{
"to": "Sarah"
"content": null
}
]
It's also important to keep in mind whether the operation will be atomic or not. If one message contains invalid data, you may or may not reject the whole request.
If the operation is atomic, you can use 400 or 422 to report invalid data. If the operation is not atomic you could use 207 to report the result of the operation of each resource.
I have one question that i am finding hard to clearly identify the correct answer.
My API has one endpoint that does pagination. So, in the response i have to return to the client the total number of lines afected by the query. The count of records in practice.
I have read that, i should be passing metadata like what i want in the body, enveloping it, but i have also read that, it is not ok to afect the body with meta-data and that the future is to return only non meta-data on the body meaning that it must be on the response header.
O'reilly
If the information you are conveying through a custom HTTP header is important for the correct interpretation of the request or response, include that information in the body of the request or response or the URI used for the request. Avoid custom headers for such usages.
So, my question is, what is the correct approach to the problem? Should i pass the number of lines in response headers or put it in the message body.
Thank you very much.
For pagination, you could use an envelope in the response payload:
{
"data": [...],
"paging": {
"first": "http://api.example.com/foo?page=1&size=10",
"previous": "http://api.example.com/foo?page=2&size=10"
"next": "http://api.example.com/foo?page=4&size=10"
"last": "http://api.example.com/foo?page=5&size=10"
}
}
A similar approach is described in the RFC 5005: each page of results is a separate resource, which contains hyperlinks to the previous and next page of results
You also could use the Link header (line breaks are just for readability purposes):
Link: <http://api.example.com/foo?page=1&size=10>; rel="first",
<http://api.example.com/foo?page=2&size=10>; rel="previous",
<http://api.example.com/foo?page=4&size=10>; rel="next",
<http://api.example.com/foo?page=5&size=10>; rel="last"
Check the link relations registered in IANA.
For returning the number of records, I've seen some APIs using custom headers such as X-Total-Count, but I don't recommend such approach. Send those details in the response payload then.
I've got a lot of API endpoints to document and the payloads of the POST and PUT requests can be complicated. I am documenting them with apiblueprint. I really like the way apiblueprint allows me to document URI parameters. It looks good and lets you provide the reader with all of the information they need such as (required, String or Integer, list choices/values and provide an example).
When we look at the Request section, however I'm not seeing how to provide the same level of pristine documentation. The request sections that I've seen just provide an example request.
Say we are dealing with a simple payload that just takes an integer named id that is required. Currently my request section would look like this,
Headers
Content-Type: application/json
Body
{"id":"123"}
Is the request body supposed to be this sparse? What is the best way to convey to my users all the constraints/requirements for my REST payloads?
If I understand you correctly, you are looking for a way to documen your request paramters (headers, body, etc.)
If that's the case, then use the Schema section, and write a well documented JSON-Schema
for example you current simple request will look like this:
Request
+ Headers
Content-Type: application/json
+ Schema
{
"type":"object",
"properties":{
"id": {
"type" : "string",
"required": true
}
}
}
+ Body
{"id":"123"}