Usage of GET, PUT and DELETE HTTP methods in RESTful web-services - java

I am working on a Ticket Reservation application. I am required to build a web-service which takes in request for cancellation, checks with a downstream system (via SOAP), whether it can be cancelled, and returns the appropriate response to the calling system after updating my tables.
I have to build a bunch of similar web-services for cancellation, rescheduling, et for which I'm planning to use RESTful web-services
This I'm planning to achieve using the POST method of the REST API, using JAX-RS. I could see that all the web-services I'm going to build suit the POST verb, and the other HTTP methods (GET, POST and DELETE) doesn't seem like they need to be used here. In that case what is the actual use case of these HTTP methods in REST? Am I right in using only POST?

Your REST resource is the ticket. Use GETs to read the ticket, PUT to modify the ticket state, and DELETE to do a logical delete (cancellation).
For any other operation, use the wildcard operation POST.
Have a look at this blog post Brief Introduction to REST, where the author goes through the core REST principles.

For the purpose of a cancellation, I would actually use the DELETE method. In the case of a successful cancellation, return a 200 with either response body confirming success or a response body containing the details of the reservation. Or a 204 if you don't want to return a body.
If it can't be canceled, you have your choice from the 400 series of errors (e.g. 404 if there is no such reservation, 403 if the request is forbidden, etc.) or the 500 series if there is a bug or malfunction.
You will certainly use the other HTTP verbs for all the other reservation actions--making a reservation, changing it, etc.

Consider your Ticket Reservations as your application resources.
Clients to your application would:
submit GETrequest to retrieve a representation (XML, JSON or anything else) one or many ticket reservations (given the URL they use, eg: /tickets to retrieve all of them - or all they are allowed to see, /tickets/1to retrieve a representation of the Ticket Reservation whose id is 1, tickets/?start=0&size=10 for paginated content, etc.)
submit POST requests on /ticketsto create a new reservation (and the response would provide the client with a location giving the location of the created reservation)
submit a PUT request to /tickets/1 (with a representation of the new reservation in the request body) to update the reservation identified by 1
submit a DELETE request to /tickets/1 to delete the reservation identified by 1
The main idea behind the use of such verbs is that the URLs should identify resources (and not actions), and the HTTP verb would be the action.
If you use everything with POST, you'll be more or less doing SOAP.
This article will give you more information on hat I tried to hihlight above: http://martinfowler.com/articles/richardsonMaturityModel.html

There's quite a lot to say about designing RESTful applications. You really should read one or more of these books: "Restful Web Services" - http://amzn.com/0596529260, "RESTful Web APIs" - http://amzn.com/B00F5BS966, "REST in Practice: Hypermedia and Systems Architecture" - http://amzn.com/B0046RERXY or "RESTful Web Services Cookbook" - http://amzn.com/B0043D2ESQ.
Get a cup of coffee and enjoy some reading :-)

Related

Spring REST - Proper PUT functionality when resource does not already exist

I am building a REST API using Spring and implementing the PUT functionality. I am trying to handle the scenario in which the client tries to PUT to a uri where the resource does not already exist. In this scenario, per the PUT spec, a new resource should be created at that ID. However because of the ID generation strategy I am using (#GeneratedValue(strategy = GenerationType.IDENTITY)), I cannot create resources with IDs out of sequence. The database must use the next available value. However, according to the w3 spec on PUT...
If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI.
If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
In this case, I can do neither of these. I cannot create a new resource at the existing URI due to the ID generation restrictions, and I cannot send a 301 Moved Permanently response because according to How do I know the id before saving an object in jpa it is impossible to know the next ID in a sequence before actually persisting the object. So I would have no way of telling the client what URI to redirect to in order to properly create the new resource.
I would imagine this problem has been solved many times over because it is the standard PUT functionality, yet I am having trouble finding any other people who have tried to do this. It seems most people just ignore the "create new resource" part of PUT, and simply use it as update only.
What I want to do is just go ahead and create the new resource, and then send the 301 Moved Permanently to redirect the client to the true location of the created resource - but as we see above, this violates the definition of PUT.
Is there a spring-y way to solve this problem? Or is the problem unsolved, and the true standard practice is to simply not allow creation of new resources via PUT?
If the server cant processes the request due to an error in the request, just return a 400.
400 Bad Request -
The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, size too large, invalid request message framing, or deceptive request routing).

Designing REST api for function calls

So I am building a REST APi that will be responsible for running various jobs on a special hardware.
So I understand that REST is used for accessing resources and not calling functions.
So what are the recommendations and best way to design an API for responsible for calling functions.
For example I will have an api job/run which will return the PID of job if job was sucesfully ran.
I'll also have a job/{pid} for accessing information about a given job. and job/cancel/{pid} for stopping said job.
So what are the recommendations and best way to design an API for
responsible for calling functions
Create a user: POST /users
Delete a user: DELETE /users/1
Get all users: GET /users
Get one user: GET /users/1
To GET Record
Bad designs
GET /FetchUsers // To fetch all records
GET /getAllUsers/12 // To fetch specific records
Preferred Designs
GET /users //To fetch all records
GET /users/12 // To fetch specific records
To Crete Record
Bad designs
POST /createUsers //To create users
GET /createrecordforUsers //To fetch all records
Preferred designs
POST /users //To create users records
To Update Record
Bad designs
PUT /updateUsersid // To update user
POST /id/modifyuser // To update users
Preferred designs
PUT /users/:id // To update users
To Delete Record
Bad designs
DELETE /deleteuser/id //To delete users
POST /id/removeusers //To delete users
Preferred designs
DELETE /users/:id // To delete users
Below points should be considered
Platform independence . (Any client should be able to call the API, regardless of how the API is implemented internally)
Service evolution .(The web API should be able to evolve and add functionality independently from client applications.)
A resource has an identifier, which is a URI that uniquely identifies that resource. For example, the URI for a particular customer order might be:
Request : GET -> https://domain/orders/1
Response :
JSON
{"orderId":1111,"amount":99.90,"productId":1,"quantity":1}
The most common operations are GET, POST, PUT, PATCH, and DELETE.
GET retrieves a representation of the resource at the specified URI. The body of the response message contains the details of the requested resource.
POST creates a new resource at the specified URI. The body of the request message provides the details of the new resource. Note that POST can also be used to trigger operations that don't actually create resources.
PUT either creates or replaces the resource at the specified URI. The body of the request message specifies the resource to be created or updated.
PATCH performs a partial update of a resource. The request body specifies the set of changes to apply to the resource.
DELETE removes the resource at the specified URI.
REST APIs use a stateless request model. HTTP requests should be independent and may occur in any order, so keeping transient state information between requests is not feasible.
We can return response with hypermedia links as spring boot having this feature
[Spring Boot:] https://spring.io/guides/gs/rest-hateoas/
https://domain/orders (Better)
https://domain/create-order (Avoid)
A resource doesn't have to be based on a single physical data item. For example, an order resource might be implemented internally as several tables in a relational database, but presented to the client as a single entity. Avoid creating APIs that simply mirror the internal structure of a database.
A client should not be exposed to the internal implementation.
Avoid requiring resource URIs more complex than (order/collection/item/details)
Summary
- Pagination Support : /orders?limit=25&offset=50
- Error handing :
- API Version (avoid as much as if possible)
Refer here https://www.openapis.org/blog/2017/03/01/openapi-spec-3-implementers-draft-released

Watson Content Analytics: How to make web crawler plug-in to get data, sending POST request?

I have WCA 3.5.0 server and I need to get documents from the site, using web crawler.
The problem is in the fact that I have to send a POST request to the site to get some data (initialy my site consists only of a form with some fields and submit button to send the request to the server). So, my POST request body should be something like that:
{"DateFrom":"2000-01-01T00:00:00","DateTo":"2030-01-01T23:59:59","Bundles":[{"Name":"the test name that i passed","Type":-1}],"Company":[],"Transaction":[],"Text":""}
I was thinking about making a a prefetch plugin for a web crawler.
But from the documentation I've found it looks like it is hardly possible:
"The first element ([0]) in the argument array that is passed to your
plug-in is an object of type PrefetchPluginArg1, which is an interface
that extends the interface PrefetchPluginArg. This is the only
argument and the only argument type that is passed to the prefetch
plug-in."
PrefetchPluginArg1 class has only getHTTPHeader(), setHTTPHeader(), getURL(), setURL(), doFetch(), setFetch(),
where:
The getHTTPHeader method returns a String that contains the all of
the content of the HTTP request header that the crawler sends so that
the crawler can download the document.
The getURL method returns the URL (in String form) of a document that
the crawler downloads. You can use this URL to decide if the document
requires additional information in the request header, such as a
cookie.
And it looks like there is no way to change request body.
So, is it realy possible to control POST request body, but not only header, and if it is so, can you please, share some information about the ways of solving this task?

How to build HTTP DELETE request with JSON encoded body using AsyncHttpClient

I need to write a HTTP client which to communicate with Floodlight OpenFlow controller via its REST API.
For testing I did it in python, and it worked OK. But now I'm in a situation where it has to be done in Java, of which I'm admittedly still at the beginner's level. One of my apps uses AsyncHttpClient to dispatch async GET requests, and works just fine. Now as a Floodlight's REST client, it has to do POST and DELETE with JSON encoded body. My code for an async POST request works very much as expected.
But no luck with DELETE.
Somehow it doesn't write JSON string into its request body.
The code is almost identical with POST. For debugging, I don't feed an AsyncCompletionHandler instance to execute() method.
System.out.println(ofEntry.toJson()); // this returns {"name": "xyz"} as expected.
Future<Response> f = httpClient.prepareRequest(new RequestBuilder("DELETE")
.setUrl("http://" + myControllerBaseUrl + urlPathFlowPostDelete)
.setHeader("content-type", "application/json")
.setBody(ofEntry.toJson())
.build()).execute();
System.out.println(f.getStatusCode()); // returns 200.
System.out.println(f.getResponseBody()); // returns {"status" : "Error! No data posted."}.
Just to make sure, I peeped into packet dump with wireshark, and found out the server isn't lying :)
The author of the library has written an extensive amount of relevant, valuable information, but unfortunately I can't find example code specifically for building a DELETE request.
I'd very much appreciate any suggestions, pointers, and of course pinpoint solutions!
Not sure that replying to my own question is appropriate here, but I have just found a related thread at the floodlight-dev Google group.
Problem with Static Flow Pusher DELETE REST method
So this could be a problem with Floodlight REST API which requires message body for a DELETE request to identify what to be deleted, whereas AHC is simply compliant with RFC2616.
I will follow the thread at Google group, and see how it will conclude among developers.

AS2: Does xml.sendAndLoad use POST or GET?

All,
I'm trying to find out, unambiguously, what method (GET or POST) Flash/AS2 uses with XML.sendAndLoad.
Here's what the help/docs (http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002340.html) say about the function
Encodes the specified XML object into
an XML document, sends it to the
specified URL using the POST method,
downloads the server's response, and
loads it into the resultXMLobject
specified in the parameters.
However, I'm using this method to send XML data to a Java Servlet developed and maintained by another team of developers. And they're seeing log entries that look like this:
GET /portal/delegate/[someService]?svc=setPayCheckInfo&XMLStr=[an encoded version of the XML I send]
After a Google search to figure out why the POST shows up as a GET in their log, I found this Adobe technote (http://kb2.adobe.com/cps/159/tn_15908.html). Here's what it says:
When loadVariables or getURL actions are
used to send data to Java servlets it
can appear that the data is being sent
using a GET request, when the POST
method was specified in the Flash
movie.
This happens because Flash sends the
data in a GET/POST hybrid format. If
the data were being sent using a GET
request, the variables would appear in
a query string appended to the end of
the URL. Flash uses a GET server
request, but the Name/Value pairs
containing the variables are sent in a
second transmission using POST.
Although this causes the servlet to
trigger the doGet() method, the
variables are still available in the
server request.
I don't really understand that. What is a "GET/POST hybrid format"?
Why does the method Flash uses (POST or GET) depend on whether the data is sent to a Java servlet or elsewhere (e.g., a PHP page?)
Can anyone make sense of this? Many thanks in advance!
Cheers,
Matt
Have you try doing something like that :
var sendVar=new LoadVars();
var xml=new XML("<r>test</r>");
sendVar.xml=xml;
sendVar.svc="setPayCheckInfo";
var receiveXML=new XML();
function onLoad(success) {
if (success) {
trace("receive:"+receiveXML);
} else {
trace('error');
}
}
receiveXML.onLoad=onLoad;
sendVar.sendAndLoad("http://mywebserver", receiveXML, "POST");
The hybrid format is just a term Macromedia invented to paint over its misuse of HTTP.
HTTP is very vague on what you can do with GET and POST. But the convention is that no message body is used in GET. Adobe violates this convention by sending parameters in the message body.
Flash sends the same request regardless of the server. You have problem in Servlet because most implementation (like Tomcat) ignores message body for GET. PHP doesn't care the verb and it processes the message body for GET too.

Categories