How to Access REST Service in Jax-RS using PHP - php

I Developed a REST Service in Jax-RS, and I have some functions that use the POST method, like:
Auth_User()
Get_List()
Insert_Data(id,name,data)
I need to access these functions using PHP cURL. What I basically need is to work the functions from the PHP files, so that my REST Service can work like Facebook App development.
how can I do this using cURL?

You can use the CURL library with it's wide range of options to perform GET/POST/HEAD etc. requests that you would need to communicate with your REST server.
As for parsing data, you would have to take a look at either json_decode() if you get json objects back, or e.g. SimpleXml if you need to parse it as XML.
See this site here for a decent example of querying the yahoo REST api in php/curl:
http://developer.yahoo.com/php/tutorials/water_bug_tutorial-making_rest_request.html

There is no such thing as a REST server. The question you are asking is "How do I make an HTTP request from PHP?" What technology the server is implemented with is absolutely irrelevant. At least it should be!

Related

How should an API on the same host be implemented through PHP

I have tried googling for related topics for this but was unable to find anything that answered my question so here I am.
I am going to be building a REST API for my web based application to improve scalability and allow me to easily implement site updates and build other applications. However, in my research I have not been able to figure out a way to use this API within PHP itself. As it currently stands, the API will not be public and will be hosted on the same server as the website hence my question.
The website currently uses PHP to load in content server side and then JavaScript to dynamically add content and embellish the user experience. I would like to keep it this way but have all requests including PHP ones to go through the API. Obviously the JavaScript will use an HTTP request going to a specific endpoint e.g "htp://example.com/user/123" but it seems cumbersome to do the same process using curl with PHP when the API is on the same host.
If I understand correctly removing the HTTP request from the mix will mean that it is not restfull but that is not an issue. So:
1: How should I make calls to the API from PHP?
2: How should I maintain the user session? Bearing in mind that the session should not be maintained by the API and JavaScript will send all neccesary data for authentication with the API call.
Use Zend HTTP Rest Client - it is having powerful rest architecture
Yes - you are right, you cannot maintain sessions when using API, so try to use another way for maintaining authorization like create some class which will check your authorization based on the API response
Use some kind of token which is unique for each user and pass it with header authorization.

Should Rest API accept POST array or JSON string?

I've been reading a few REST tutorials and some of them says that in order to send data to a rest API you should send post data as an array, which is something like this:
$data = array('foo' => 'bar');
$rest->post($data);
Then there are others that say you should send JSON data like this:
$data = array('foo' => 'bar');
$data = json_encode($data);
$rest->post($data);
Not sure if there's a standard way of doing this or either if is fine but what is generally recommended when designing API's?
EDIT: There seems to be confusion. To clarify I agree JSON should be used for client consumption but this question is about SERVER consumption. Meaning should the SERVER accept JSON or POST data from its clients?
If you're the one creating the RESTful API, meaning your application is the server and is accepting requests, then your question seems confusing. Your application will not be sending any POST data; clients will be sending POST data to you.
With that being said, having an API which will accept JSON-encoded requests is possible, though would really only be useful for very niche scenarios. The vast majority of clients will be POSTing data to your API in the application/x-www-form-urlencoded format. PHP handles this behind the scenes for you, and exposes the data as the $_POST superglobal.
If you're talking about responding to POST requests, and what format you should use, then that will depend on what format the client wants you to send it in. The client will either specify this in the Accept header, or some APIs allow it to be specified in the URL (e.g. foo.com/some/thing/123.json or foo.com/some/thing/123/json). The client isn't required to tell your application what format it wants, so it's up to you to pick a sensible default. Most APIs will use JSON these days.
I've never heard of an API that understood serialized PHP array format, though, so I don't know what resources you've been reading, but I'm pretty sure you misunderstood what they were suggesting.
Actually, I think this is a pretty good question. don't know why it got downvoted.
Also, contrary to what I saw written in some comments, the client can use any language he wants, not only javascript. And it's not the server job to know which language was used to "build" the request, just that the request is valid. This makes more sense if you think that the entity making the request can actually be another server (think about a proxy server used to send post requests across domains).
That being said, personally, I think it's better for the server side to consume a XML or JSON. The main reason is validation.
It's easier to validate a XML or JSON against a schema.
Also the schema can be made public, and a well designed schema can describe webservice by itself. The client can even use the same schema to validate the request prior to sending it to the server.
Passing an url encoded form is also valid, of course. And can be validated server side as well. SO i think, down the road, it's just a matter of preference.
Also, check this discussion in SO, it regards the same topic:
JSON vs Form POST
You should think about the clients that will consume the API. A HTML5\AJAX client will probably want JSON data, while other clients (Silverlight or native mobile apps) might be better at consuming XML.
One great framework\platform for writing REST API's is looking to be Microsoft's Web API (based on ASP.NET MVC). The product succeeds the WCF framework and allows users to write REST API's in a MVC environment. One feature is that it chooses a serialization provider based on the HTTP Accept header.
So if a client Accepts application/json they work with the service in JSON and if the accept XML they work with the service in XML. You can also write your own object serializer and plug it into the framework.
More information: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/video-your-first-web-api
Most of the time you would want to stick to receiving POST data but I think receiving json data does have its uses for example when it comes to batch requests.
The Facebook API uses it.
You don't need to do file_get_contents('php//input'). From the facebook documentation you could just do something like this:
curl -X POST "http://example.com/batch" -d 'batch={ "param" : 1, "param2" : "2"}'
Then in the PHP code, if you're using PHP, you can get it through the $_POST parameter and do a json_decode.
var_dump($_POST);
array(1) {
["batch"]=>
string(30) "{ "param" : 1, "param2" : "2"}"
}
var_dump(json_decode($_POST['batch'], true));
array(2) {
["param"]=>
int(1)
["param2"]=>
string(1) "2"
}
JSON makes more sense, since it is language-independent and can be useful when API scales.
I am currently developing a REST API and I was asking myself the same question. After some research I found out that is no standard and is totally up to you.
You are developing the server side so you can decide how data should be sent to you. The client need to adapt to your design.
Personally I choose to receive all POST and PUT data as JSON directly in body.
The point is to reuse the HTTP implementation that already exists.
HTTP is built to accept many different content-types and you only need to specify which you are using in the headers.
A REST API that accepts the various formats and works off the content-type header is refreshing. You can submit x-www-form-urlencoded values from an HTML webpage or make an AJAX request with raw JSON and there is no confusion as long as everyone is following protocol.
As a developer you must choose the support your app will provide because you can't support everything. Typically it boils down to the support or convenience of your own environment -- nobody wants to reinvent the wheel.
Many frameworks that are designed with building APIs in mind, handle the most popular content types at a lower level. They may also encode the response data according to the "Accept" header.
Implement whatever you think will be used most first or find a framework that already speaks HTTP and takes care of all of that for you.

search api to use in external websites

I am new to api development, so don't know whether this is feasible or not.
I have a website(http://www.mysite.com/) which consists of data and i need to develop an api or somehow use this site's data to use it in another websites.
My requirement is other external websites(http://www.externalwebsites.com) need to search the data from my main site (http://www.mysite.com/). http://www.externalwebsites.com/ will send search string to http://www.mysite.com/ and it will send back result and show them in http://www.externalwebsites.com/.
i need to use ajax calls in http://www.externalwebsites.com/ for searching data, so my question is
Is this whole process feasible ?
Sure, you can use JSONP, supported by default in libraries like jQuery.
http://docs.jquery.com/Release:jQuery_1.2/Ajax#Cross-Domain_getJSON_.28using_JSONP.29
A good way is to use SOAP web-service:
http://plutov.by/post/web_service_soap
REST: http://searchsoa.techtarget.com/definition/REST
SOAP: http://tr.wikipedia.org/wiki/SOAP
oAuth: http://oauth.net/2/ (this is used by popular sites like Facebook, Google, Yahoo, Twitter)

Possible to use Javascript to get data from other sites?

Is it possible for a web page using Javascript to get data from another website? In my case I want to get it for calculations and graphing a chart. But I'm not sure if this is possible or not due to security concerns. If it is considered a no no but there is a work around I would appreciate being told the work around. I don't want to have to gather this information on the server side if possible.
Any and all help is appreciated.
Learn about JSONP format and cross-site requests (http://en.wikipedia.org/wiki/JSON#JSONP).
You may need to use the "PHP-proxy" script at your server side which will get the information from the websites and provide it to yours Javascript.
The only reliable way is to let "your" webserver act as a proxy. In PHP you can use curl() to fire a HTTP request to an external site and then just echo the response.
You can't pull data from another server due to the same origin policy. You can do some tricks to get around it, such as putting the URL in a <script> tag, but in your case it wouldn't work for just parsing HTML.
Use simple_dom_html, to parse your data server side. it is much easier than doing it in JavaScript anyways.
A simple way you might be able to do this is to use an inline iframe. If the web page you are getting the data from has no headers, or you can isolate the data being pulled in (to say an image or SWF), this might work.
cross-domain javascript used to be impossible, using a (php-)proxy was a workaround for that.
jsonp changes this entirely, it allows to request javascript from another server (if it has an API that supports jsonp, a lot of the bigger webplayers like google, twitter, yahoo, ... do), specifying the callback-function in your code that needs to be triggered to act on the response.
the response in javascript will contain:
a call to a callback-function you defined
the actual payload as a javascript-object.
frameworks like jquery offer easy support for jsonp out of the box.
once you have the raw data you could tie into google chart tools to create graphs on the fly and insert them in your webapp.
Also worth considering is support for XMLHttpRequest Access Control which is support in some modern browsers.
If the service provider that you are trying to access via a web page has this set up, it is a very simple call to XMLHttpRequest and you will get access to the resources on that site without the need for JSONP (especially useful for requests that are not GET, i.e. POST, HEAD etc)

get values of elements from another site (rapidshare)

I am developing a script in php to manage my rapidshare accounts (for learning purposes), i wanted to know how can we login remotely and get accounts details on my site, something that api does, the details like traffic left, expiry date, etc.
Uncertain what exactly your question is, but it probably helps to take a look at the Rapidshare API. Additionally you probably want to make yourself familiar with the following functions/ components: fopen and curl to use the api/load the site. To get specific parameters out of the content I suggest using ereg or the xml functionality.
With PHP you could use either Curl, PHPSimpleHTMLDomParser, Snoopy, or phpQuery to grab the contents from the remote page. Be mindful that some websites require a user_agent, in which case you could setup one through ini_set prior to running your script.
You could use cURL to send HTTP requests from your script to the site. There are also ready-made solutions for PHP, such as Snoopy, which will let you do things like posting a form or scraping a page, without having to use cURL directly.
Since Rapidshare does not provide an API interface to their service, the only way is to use an HTML parser available for PHP, login with the script, and parse the values.
Update: Rapidshare does provide an API as merkuro has stated in his post.

Categories