So this is sort of a 2 part question, so I apologize in advance if I’m duplicating questions here.
I’m in the process of implementing a REST API in PHP for a web app that I’m building for work. Thus far, I have implemented a function which will query a User database table and return the results in JSON encoding.
The way I make the request (which uses the GET method, btw) is making the request to the URL: http://api.my-wicked-awesome-webapp.com/?method=getAllUsers. The result is then JSON encoded and echo’d out as plain text on the web page. Now, that works, and there’s really nothing wrong with doing it that way, however in my mind, that format looks a little clunky.
Part one of my question: How can I go about parsing a request (in this case, a GET request) to a URL such as http://api.my-wicked-awesome-webapp.com/users/, which will do the same thing as the first example URL?
Part two of my question: As it goes right now, if I were to type in the first example URL into my web browser, a JSON encoded result would be displayed on the web page. How would I go about pulling that data into some other web page? Could I use JQuery.ajax() to make that request and pull in the data? And if so, how should I go about doing that?
As always, if any of my questions were worded poorly, I’ll be more than happy to rephrase anything. Thanks in advance for any answers!
You need mod_rewrite on
.htaccessfile,Better use
This will map any url like
http://api.my-wicked-awesome-webapp.com/ANY_NAME/tohttp://api.my-wicked-awesome-webapp.com/index.php?method=ANY_NAMEYou can call
JQuery.ajax()from your domainapi.my-wicked-awesome-webapp.com. But not fromforeign.domain.com. If you want to do it from another domain you need to use JSONP.Using JSON you’d call as,
Using JSONP you’d call it as
And in
index.phpyou need to wrap the output with$_GET['callback']; Something likeecho "$_GET['callback'](".$JSON_DATA.")";That’ll invoke the callback on loading.