Sample Request for a REST-API in Java or PHP - java

I am looking at extracting data from a survey tool using their API. Being fairly new to APIs, I went through their documentation, few videos and figured out a little of what's happening.
But along with the Method and Attributes, they also have a sample request in Java/PHP and a sample response. Now the sample response is the JSON file fomat I'm expecting back but what do I have to do with a sample response?
As in, from all the videos I have seen you call an API using a particular URL. What is this sample request used for? Is it for using it in your own code?
I know its quite a silly question but any input would be much appreciated.

Assume you have a system that manages "virtual machines" for you; and that offers an API like:
/system/create-new-virtual-machine
/system/{virtual-machine-id}/start
So: your client would first call the first API method to somehow define a new virtual machine (providing all the required data to create a configuration).
Obviously, when you create a new thing, that should result in a new URI; which you would use later on to make other calls. In our example, the create call would return 200 ... and give you the URI for the newly created vm within the result body.
Long story short: just think of your REST api as the interface of a component/module your code is dealing with. Some of the API operations just tell you "fine, I passed" ... but others will want to give you information back. And that is what you need the response body for.

Related

How to return project details (name and other metadata) using rest api?

I’m fairly new to REST API and working on a product where client X interacts with n number of servers (Y1, Y2,…Yn) to retrieve different type of data from backend, using POST requests.
Now I also want to retrieve some metadata related to each server (file names, project name etc.) for our internal use-case in client X. Note: This should be a separate request.
How should I implement this using Rest?
Can I use OPTIONS method for this?
I tried implementing this with GET method but not sure if it’s best approach.
Since you are going to retrieve information the GET is the most appropriate. POST instead should be used to 'insert' fresh new datas. I would suggest to take a look at the meaning of all HTTP verbs (POST,GET,PUT,PATCH,DELETE) in order to understand them.

Which HTTP method to use for this client request?

I am developing a REST web service in Java which on clients' request processes the request body and gives the output to the client. The request body sent by the client consists of a GO(programing language) program which the server executes(runs) on the server machine and returns the standard output of the program back to the client. Now since the request body contains some text(program), I cannot use HTTP GET method to do that. I can use PUT or POST, but I have learnt that they(PUT and POST) are generally used for updating/creating a resource. Since, I am not creating any resource here, is it conceptually correct to use PUT or POST. If not, which is the HTTP method that I need to use?
Looking at the problem you are solving and comparing to an existing production solution , I suggest that you can use POST in your scenario.
Reasoning - Example Production code solving similar problem:-
Assuming that the problem you are trying to solve is this:-
Clients submit code in Go programming language, Your server compiles it, runs it and then gives the output. Assuming also that, it is somewhat similar to many online coding websites like hackerEarth, their API documentation page and the sample python code provided show that we can use HTTP:POST to submit code to the server for its processing.
Reasoning - RFC for HTTP POST, PUT :-
POST is designed to allow a uniform method to cover the following functions:
Providing a block of data, such as the result of submitting a
form, to a data-handling process;
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server.
Referring to the above statements, we can conclude that in the context of this problem which you are solving, you are requesting the server to do some data-handling for the enclosed entity, so you can use POST.

how to consume a Restful Web Service (Restful API) in Java

I just want to know the high level steps of the process. Here's my thought on the process:
Assumption: the API returns JSON format
Check the API document to see the structure of the returned JSON
Create a corresponding Java class (ex: Employee)
Make Http call to the endpoint to get the JSON response
Using some JSON library (such as GSON, Jackson) to unmarshall the JSON string to Employee object.
Manipulate the Employee object
However, what if the API returned JSON is changed? it's really tedious task to exam the JSON string every now and then to adjust the corresponding Java class.
Can anyone help me out with this understanding. Thanks
You describe how to consume a json over http API, which is fine since most of the APIs out there are just that. If you are interested in consuming Restful HTTP resources however, one way would be:
Check the API documentation, aka. the media-types that your client will need to support in order to communicate with its resources. Some RESTafarians argue that all media-types should be standardized, so all clients could potentially support them, but I think that goes a bit far.
Watch out for link representations, and processing logic. media-types do not only describe the format of the data, but also how to process them. How to display it if its an image, how to run code that might be part of the message, how to layout onto the screen, how to use embedded controls like forms, etc.
Create corresponding Java classes. If the resources "only" describe data (which they usually do in API context), then simple Java classes will do, otherwise more might be needed. For example: can the representation contain JavaScript to run on the client? You need to embed a JavaScript engine, and prepare your class to do just that.
Make call to a bookmarked URI if you have it. There should be no hardcoded SOAP-like "endpoint" you call. You start with bookmarks and work your way to the state your client need to be in.
Usually your first call goes to the "start" resource. This is the only bookmark you have in the beginning. You specify the media-types you support for this resource in the Accept header.
You then check whether the returned Content-Type matches one of your accepted media-types (remember, the server is free to ignore your preferences), and then you process the returned representation according to its rules.
For example you want to get all the accounts for customer 123456 for which you don't yet have a bookmark to. You might first GET the start resource for account management. The processing logic there might describe a link to go to for account listings. You follow the link. The representation there might give you a "form" in which you have to fill out the customer number and POST. Finally, you get your representation of the account list. You may at this point bookmark the page, so you don't have to go through the whole chain the next time.
Process representation. This might involve displaying, running, or just handing over the data to some other class.
Sorry for the long post, slow day at work :) Just for completeness, some other points the client needs to know about: caching, handling bookmarks (reacting to 3xx codes), following links in representations.
Versioning is another topic you mention. This is a whole discussion onto itself, but in short: some people (myself included) advocate versioning the media-type. Non-backwards compatible changes simply change the media type's name (for example from application/vnd.company.customer-v1+json, to application/vnd.company.customer-v2+json), and then everything (bookmarks for example) continues to work because of content negotiation.
There are many ways to consume RESTful APIs.
Typically, you need to know what version of the API you are going to use. When the API changes (i.e. a different version is exposed) you need to decide if the new functionality is worth migrating your application(s) to the latest and greatest or not...
In my experience, migrating to a new API always requires some effort and it really depends on the value of doing so (vs. not doing it) and/or whether the old API is going to be deprecated and/or not supported by the publisher.

How to: Accessing RESTful Web Services with Play Framework 2.1 for Beginners

I am fairly new to many of the concepts and technologies being used in this question so I would appreciate a little understanding and help for a beginner from the community. I am using the Play Framework version 2.1.3 and I need to POST data to a RESTful web service so that it can be inserted into a remote database. An XML response will be returned indicating either success or failure.
I am sure you are aware that the documentation for the Play Framework is quite lacking and is in no way helpful to beginners, therefore I am unsure of how to accomplish this task with best practices in mind. I am looking for a Java solution to this problem, I do not have the time at present to learn the Scala language. My experience with Web Services is fairly limited, normally I would implement a DAO design pattern (or use one of the many available ORM libraries depending on needs) within my application and use JDBC to connect directly to the database. That is not an option here.
My first question would have to be, is there a recommended design pattern for accessing web services? Then, considering the Play MVC framework, how would one best implement such a design pattern, package the data (assuming the application has already captured and validated data from the user), send it off and process the responses back to the user?
I know it is a fairly lengthy question however my intention behind this is to create a knowledge base of sorts for beginners who can easily come in with limited experience, read, understand and replicate what they find here to produce a working solution. Having searched the web quite extensively, I have found a few disjointed snippets but nothing concrete involving these technologies and no up-to-date tutorials. Thank you for your time.
Creating requests is straight-forward. First you provide a URL. There are various methods to add content types, query parameters, timeouts, etc. to the request. Then you choose a request type and optionally add some content to send. Examples:
WSRequestHolder request = WS.url("http://example.com");
request.setQueryParameter("page", "1");
Promise<Response> promise = request.get();
Promise<Response> promise = WS.url("http://example.com").post(content);
The complicated part is to send it and use the response of the request. I assume you have a controller that should return a Result to the user, based on the web service's response. The result is usually a rendered template or maybe just a status code.
Play avoids blocking by using Futures and Promises. The controller's async method takes a Promise<Result> and returns a result (the future value) at some point later. A simple to use promise is provided by the get and post methods shown above. You don't need to care about their implementation, you just need to know that they promise to provide a Response once the request is complete.
Notice the problem here: When creating a request with WS.url("...").get() it will give you a Promise<Response> even though async takes a Promise<Result>. Here you have to implement another promise yourself, which will convert the response to a result using the map method. If you follow the Play documentation, this will look a bit confusing, because Java doesn't has closures (yet) and everything has to be wrapped in a class. You don't have to use anonymous classes inside the method call though. If you prefer more clean code, you also can do it like this:
return async(
request
.get() // returns a `Promise<Response>`
.map(resultFromResponse) // map takes a `Function<Response, Result>` and
// returns the `Promise<Result>` we need
);
The object resultFromResponse may look like follows. It's actually just like a cumbersome definition of some kind of callback method that takes a Response as only argument and returns a Result.
Function<Response, List<T>> resultFromResponse =
new Function<Response /* 1st parameter type */, Result /* return type */>() {
#Override
public Result apply(Response response) {
// example: read some json from the response
String message = response.asJson().get("message");
Result result = ok(message);
return result;
}
};
As #itsjeyd pointed out in the comments, when calling webservices in Play 2.2.x you don't wrap the call in async any more. You simply return the Promise<Result>:
public static Promise<Result> index() {
return request.get().map(resultFromResponse);
}

How to read a response of a servlet using PHP

I would like to send a request to a Java Servlet from PHP and receive the response from the same and show it on the PHP page. How should this be done?
Thanks and Regards
Abishek R Srikaanth
If all you want is to print the response of a GET request to an external resource plain vanilla into the PHP response, then you can use file_get_contents() for that.
<?php echo file_get_contents("http://example.com/someservlet"); ?>
The servlet's doGet() method will be invoked and whatever response it returns (which can even be a forwarded JSP) will be printed as string to the PHP response.
If you want a little more fine grained control, e.g. using POST or something, then head to curl() instead. The linked PHP manual contains several examples.
Regardless of the way, please note that whenever it returns HTML, that you should ensure that you end up with valid HTML. For example, nesting <html> tags is illegal. Pass the PHP page through the w3 validator if you're unsure. Otherwise you'd better have to parse the HTML to extract the <body> pieces of interest or to use an <iframe> instead.
<iframe src="http://example.com/someservlet"></iframe>
If I'm understanding you correctly you want to read the response of a servlet in php and then output it from php?
You can use file_get_contents to the url (Probaly not the best way, but for simplicities sake it the easiest) and then just echo the output.
For example:
$content = file_get_content('http://www.google.com');
echo $content;
But if you want to be able to login or use the session at the servlet side you will need think of something else. As each request to the server from php will be a new one, it does not store cookies etc.. like browsers do.
Hope that helps
This is a situation which might do well to be rethought, but, if there are no other options...
If there is a way to actually update the portlet, then I would recommend creating some form of service call -- SOAP, custom RPC, etc -- on the Java side. Technically this is the most correct way to do things.
Failing that, if this is a simple GET request, then use file_get_contents.
If it has to be a POST/PUT/DELETE, then you can use cURL. cURL also has the benefit of being able to handle simulated sessions, which means that you are then able to simulate a log in and actions following that (though not without some difficulty).
If you don't have cURL and you need to POST/PUT/DELETE, then the streams library might be able to give you what you need.
If you don't have the streams library or cURL and you need to POST/PUT/DELETE, then there are other means of accomplishing that, but maybe you should really re-rethink that situation.
If all of the above don't work, then you will need to tame the Spectral Wolf. The Spectral Wolf fears only fire. I can no longer help you, but if you master the Spectral Wolf, he will guide you. Godspeed.
If you really want to do that, you can create a Java app that takes parameters to populate request and response objects, instantiates a servlet, runs the correct method, gets the result and displays it, then call this Java app from PHP.
Or you can use the experimental and unrecommended PHP / Java Integration module.

Categories