How important is it to stick to the appropriate HTTP request types when designing an API? - rest

Typically when designing an API I attempt to stick to the following structure:
GET: /resources (get multiple resources)
POST: /resource (create a single resource)
GET: /resource/:id (get a single resource)
PUT: /resource/:id (update a single resource)
DELETE: /resource/:id (delete a single resource)
But sometimes when you are "getting" data the parameters being passed in start to grow beyond what you can include in a query string. For example in the GET: /resources example I provided there might be a number of filters you want to apply to the resources you are selecting.
In this case is it ok to begin using a POST so that you can include parameters in the request body? What are the drawbacks from breaking away from adherence to the structure I mentioned above?

In this case is it ok to begin using a POST so that you can include parameters in the request body?
Yes, which is to say that there are trade offs.
What are the drawbacks from breaking away from adherence to the structure I mentioned above?
It interferes with the ability of generic components to intelligently participate in the protocol.
A GET request has safe semantics; the agent can take advantage of this to do pre-fetching of resources, crawlers can explore the content freely, and so on.
Successful unsafe methods invalidate cache entries. That gets awkward when you want multiple representations of the same resource; fetching one representation via POST will evict other representations of the same resource from the cache.
If all we really wanted was RPC, we could do everything with POST. See "SOAP", for instance, where all of the messaging in built into the payload, and HTTP is just used as a dumb tunnel.

1)REST is a like design pattern for HTTP communication. It always good to follow REST, especially when you expose your API to public usage or browser to server communication.
2)You can write HTTP Requests even without having a proper REST pattern, But it will lead to unnecessary problems if its browser to server communication. Because most of the modern browsers designed using REST standards, They will understands this pattern very well. By default GET requests will be cached, instead of GET if you use POST by default it won't cache. So a new request will be fired to server each and every time. So it will lead to a lot of connections, resource, etc.
3)GET - Word itself gives you the meaning it only for getting a resource. likewise, POST and PUT for creating records, DELETE is for deleting, etc.
4)POST-VS-GET - If you use POST you can include RequestBody whereas in GET request you can't.It better to follow GET for getting a resource data

Related

Which HTTP method to use to build a REST API to perform following operation?

I am looking for a REST API to do following
Search based on parameters sent, if results found, return the results.
If no results found, create a record based on search parameters sent.
Can this be accomplished by creating one single API or 2 separate APIs are required?
I would expect this to be handled by a single request to a single resource.
Which HTTP method to use
This depends on the semantics of what is going on - we care about what the messages mean, rather than how the message handlers are implemented.
The key idea is the uniform interface constraint it REST; because we have a common understanding of what HTTP methods mean, general purpose connectors in the HTTP application can do useful work (for example, returning cached responses to a request without forwarding them to the origin server).
Thus, when trying to choose which HTTP method is appropriate, we can consider the implications the choice has on general purpose components (like web caches, browsers, crawlers, and so on).
GET announces that the meaning of the request is effectively read only; because of this, general purpose components know that they can dispatch this request at any time (for instance, a user agent might dispatch a GET request before the user decides to follow the link, to make the experience faster).
That's fine when you intend the request to provide the client with a copy of your search results, and the fact that you might end up making changes to server local state is just an implementation detail.
On the other hand, if the client is trying to edit the results of a particular search (but sometimes the server doesn't need to change anything), then GET isn't appropriate, and you should use POST.
A way to think about the difference is to consider what action you want to be taken when an intermediate cache holds a response from an earlier copy of "the same" request. If you want the cache to reuse the response, GET is the best; on the other hand, if you want the cache to throw away the old response (and possibly store the new one), then you should be using POST.

http verb to invoke services / methods

what is the best practice in defining web service that represent a non REST command invocation?
For REST, basically we use POST to create new record(s), GET to retrieve record(s), PUT to update record(s) and DELETE to remove record(s). Which http verb should I use if I just want to invoke some other non resource function, for example - to flush a system cache?
Which http verb should I use if I just want to invoke some other non resource function, for example - to flush a system cache?
HTTP request methods should be selected based on their alignment with their defined semantics.
The most important of these is to determine whether or not the semantics are safe
Request methods are considered "safe" if their defined semantics are essentially read-only; i.e., the client does not request, and does not expect, any state change on the origin server as a result of applying a safe method to a target resource. Likewise, reasonable use of a safe method is not expected to cause any harm, loss of property, or unusual burden on the origin server.
Advertising a safe link invites consumers to pre-fetch a link, or to crawl and index the representation found there.
If having Google and a billion of her closest friends flushing your system cache sounds expensive, then you probably don't want a safe method.
PUT and PATCH are unsafe methods with semantics of manipulating representations. So if you had a schema that described a system cache, a client might PUT a representation of an empty cache in the entity body, and send that to you, whereupon you could flush the cache. You could achieve a similar things with PATCH, sending a list of the edits needed to make the change.
Both of these rely on the illusion that your resources are just documents. I GET a representation of your resource, I load that into my generic editor, make changes, send my edited representation back to you, and then it's up to you to manifest those changes (or not).
But they aren't required -- if you want to simply document that
PUT /df1645af-f960-4cc4-ad7a-d0ddd29903f8
Content-Length: 0
has the side effect of flushing the system cache, the REST Police aren't going to come after you just because you've introduced a bit of RPC into the mix.
Of course, if you were doing this with HTML, then your only choice would be POST.
The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.
Which is to say, POST is always an option.
It's easy enough to imagine the flow -- you load up some bookmark, follow a system cache link, find a form with a flush cache button, and submit. The browser would create the request as described in the form elements and submit it.
So that's going to be fine too. And the REST police won't bother you for that, because that protocol is actually RESTful.
If those answers are unsatisfying, or if you are just surveying the space to know what options are available, you can review the HTTP Method Registry. To be honest, I've never found anything there I've wanted to use. But if WebDAV is your jam....

REST: What is difference between GET and DELETE, when we can implement same functionality in both?

In REST Web Services we have GET AND DELETE methods.
Generally we read GET is to get data from server like "getCountriesName" and DELETE is used to call resource which deletes particular object like "removeOrganization".
But if i implements DELETE to "getCountriesName" then it successfully returns country name.
So how both are different? Any real-time scenario?
It is technically possible, but if you make that way, then you are not following the REST standards. I would recommend to use delete to remove resources and get to query them
Looking at the Richardson Maturity Model, if you're aiming to achieve at least level 2 of REST, you'll end up with resources (Country) and HTTP VERBS:
GET /api/countries/{id}
which would also return the country's name, among other parameters.
You could also issue a DELETE request towards the same URL, provided there's an endpoint that supports this - in the backend you'll usually have methods that allow a certain HTTP VERB on them. The details of the implementation depend on the language you're using, for example in C# you would have a method with mostly the same signature, but a different attribute on top of it, like [HttpDelete]).
Thinking in terms of methods (getCountriesName/removeOrganization) is not RESTful at all, but rather SOAP/RPC.
How your service handles requests is completely up to you. You could basically create new resources on receiving GET requests or delete things using OPTION, though I highly recommend to not do so as this does not adhere to the backing protocol (HTTP in this specific case) and thus violates a basic REST constraints. Note further that a RESTful service should always adhere to and respect the supported protocols.
According to RFC 7231, one of the major differences between GET and DELETE is, that the latter one removes an association from a given resource and its functionality and also that the returned response is not cachable. This may or may not remove the data physically, the effect on consecutive DELETE or GET operations is, however, that the deleted resource should not be obtainable further. A consecutive DELETE request is issued to the server regardless of any previous request. If the resource was deleted before, the service should notify the client with a propper 404 Not Found error response if no new resource was created in between two delete operations on the same resource.
GET responses, on the other side, are cachable and thus may save work on the server by returning the result from a previous request directly from the (proxied) cache rather then issuing the request to the server. This can be fine-grained with propper cache-header settings.
The type of HTTP method to be used is more of a convention and a practice to be followed. This would give wrong information when the API s are exposed to the external systems
Refer to the blog post for detailed info

Are DELETE/PUT http verbs needed?

I don't see a huge benefit of designing a REST API service that uses PUT and DELETE to update and delete data. These 2 verbs can be easily replaced by using a POST and a unique url.
The only benefit I see of using PUT and DELETE is it cuts down the number of url's that the REST API service uses which isn't much. Are there other benefits that I'm overlooking?
This actually has not so much to do with REST, but more with the Hypertext Transfer Protocol (HTTP).
The basic idea of HTTP is that you perform a certain action (one of the HTTP methods, such as GET, POST, PUT and DELETE) on a certain resource (identified by its URL). So if you start deviating from that by adding the action into the URL (such as http://example.com/api/books/123/delete) and using a different HTTP method, you are violating the HTTP protocol.
The downsides of this might not be instantly visible (because it will still work), and might be limited if you are only using the API by yourself. However, if other programmers are using the API as well, you are creating certain expectations by stating that you have a RESTful HTTP API while you are actually not adhering to the protocol.
For instance, if calling GET /api/books/123 returns a representation of the book resource, a developer expects to be able to call PUT on that same URL to update the information on that book, and DELETE to remove the book alltogether. (of course, if he does not have permissions to do that, you don't actually remove the book but you return a 403 'Forbidden' or 405 'Method Not Allowed' status code - which are also part of the HTTP specification)
However, if you deviate from the protocol (basically inventing your own protocol), you will have to describe somewhere that instead of calling DELETE /api/books/123 developers have to call POST /api/books/123/remove/the/book. They will have to be aware of all your API's custom rules because you are not following the standard.
Another good point is made by Darrel Miller in his answer. The HTTP methods all have a certain meaning and also certain characteristics. For instance, GET is supposed to be a safe method, used to retrieve information without making any changes on the server side. And PUT and DELETE are idempotent, which means that (even though they are not safe methods like GET) you can make as many requests as you like without any unwanted side effects (deleting a book one or ten times has the same effect: the book is gone). POST however is not idempotent: if you do ten POST requests to create a new book, you will most likely end up with 10 duplicate book entries.
Because of these characteristics, developers and tools are able to make certain assumptions. For instance, a search indexer such as Googlebot will only do GET requests, in order to not break anything on the server. However, if you would be violating the HTTP specification by having a URL http://example.com/api/books/123/delete in order to delete a book, you might notice at one day that your database is completely empty because Google has been indexing your site. That wouldn't be Google's fault but yours, because you didn't follow the specification.
So to make a long story short: using a protocol or standard (such as HTTP) sets certain expectations, and if you then deviate from the protocol you will create unexpected behavior and possible unwanted side effects.
It is not required to use PUT and DELETE to get the benefits of a REST based system.
Using the more precise methods can be advantageous in certain cases. Usually it is intermediary components that take advantage of the semantics. PUT and DELETE are idempotent methods, so if some generic component receives a 503, in theory it could retry a PUT/DELETE until it gets a successful response. With a POST method, the intermediary can't do that.
With a DELETE method a client knows not to send a body. With a PUT, it knows to send a complete representation. With a POST method, you need to communicate to the client how to make the request in some other way, like a link relation.
You can live without PUT and DELETE.
This article tells you why: http://www.artima.com/lejava/articles/why_put_and_delete.html
..BUT (quote from Fielding): "A REST API should not contain any changes to the communication protocols aside from filling-out or fixing the details of underspecified bits of standard protocols, such as HTTP’s PATCH method or Link header field. Workarounds for broken implementations (such as those browsers stupid enough to believe that HTML defines HTTP’s method set) should be defined separately, or at least in appendices, with an expectation that the workaround will eventually be obsolete. [Failure here implies that the resource interfaces are object-specific, not generic.] "
(http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven)

Add data(Object) to Jersey(Restful) Response to a POST?

I want to GET an object that depend on another one sent by the client. So in normal scenario i should first POST the initial Object, then retrieve it to construct the final object and get it with GET method. How can i do it without a session? (We are in a RESTful Application ).
Is it possible to add an Object(XmlElement) in the Response to a POST request using Jersey?
I want to avoid having to do 2 operations (POST, then GET).
Is it in contradiction with HTTP Protocol?
With POST you can take an input document and produce an output document, and it doesn't require any kind of session. The POST verb really just means “do something with this”; it's much less specific in meaning than GET, PUT or DELETE. However, if the processing operation is likely to take a “long time” (which is a fuzzy concept) then you are better off creating a resource in response to the POST that tracks the processing and redirecting the client to that resource; like that, they can pick up the results once they're available. It's up to you whether you use a session to manage the resource existence, but I don't really recommend it at all; access control should be by the users identity whether or not there's a session involved, and the processing resource should be available to anyone who asks (and is authorized). You may well need to consider carefully what's involved in managing semi-transient resources (e.g., a database and expiry policy) and design your whole application carefully with those things in mind.