I'm looking to generate a RESTful API in PHP and based on my experience using them in the past my instinct is to make a PHP script for each function (since they appear at different URLs). However, I then thought that that would be odd because of the levels of hierarchy present in most REST functions I've seen and the fact that none of the REST URLs I've ever seen have any kind of suffix (ie .php). Can someone explain to me the ideal way to setup a RESTful API using PHP so that works the way you might expect a RESTful API to work?
Generally if you see domain.com/users/validate that is a clean way of accessing an API using something such as mod_rewrite (.htaccess) for my clients I generally stick with domain.com/?method=SOMETHING,etc.
Related
I want to create a pure PHP REST API and I am quite new in backend development field, but I am experienced software developer, so some concepts are known to me.
However, after watching several tutorials on how to create REST API with PHP, all instructors were using simpler examples, where no nesting exists.
Simple Example:
GET /api/category/read.php
However, I want to create something like this:
GET /api/{user_id}/{folder_id}/{file_name}/read.php
I am struggling to find any tutorial covering this with PHP. And I have spent several hours trying to figure it out by myself by trying to modify the code I have seen in Tutorial videos. I mean if I do like they do, this would mean manually creating folders in my Project Folder for each {user_id} and so forth for each sub-folder... but I do not think that such hardcoding is the solution.
I have found some SO questions here relating closely to my question, but none have satisfying answers - makes me wonder that this if this is possible to do at all. But it seems so common (for example, I know that GitHub API has just that support /{user}/repos) so I think it should be doable.
I would be really grateful if someone could help me out how to accomplish my goal. If not else, pointing to a tutorial / documentation that does just that is equivalently appreciated!
You do not need to create the folder structure to achieve this. It would be more advantageous to use something like Apache Mod Rewrite or a framework like Laravel to help avoid the need to create the file structure you are describing and have a single endpoint for handling specific routes:
Using mod rewrite with Apache2 would work something like:
.htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^api/(.+)/(.+)/(.+)/read /api/read.php?user_id=$1&folder_id=$2&file_name=$3
This would provide the URI variables in the $_GET and $_REQUEST supergobals in /api/read.php
Using the Laravel framework you can leverage their MVC approach and create dynamic routes which can capture the URL vars and deliver them to the desired Controller endpoint:
in your routes file:
Route::get('api/{user_id}/{folder_id}/{file_name}/read', Controller#read)
in the Controller:
public function read(user_id,folder_id,file_name){ /* do stuff */ }
There is alot more to know about the specifics of MVC and using Laravel to create an API, however, they have great documentation and tutorials.
Create a PHP script that receives every request (have Apache direct all requests to it), and then process the $_SERVER['REQUEST_URI'] variable to split the path into segments, storing the parts in variables of your choice. Then dispatch the request to sub-components as necessary.
I'm developing an iPhone APP and need to implement also an Web Service.
First of all I'm not a Developer and never made something big in PHP, Objective-C, xCode.
My PHP knowledge isn't also good. But let's start with my Environment.
iPhone APP (xCode 4.2, iOS5), PHP Web Service, MySQL DB
I was researching the WEB and most People tend more to REST than SOAP. I think i see also the advantages of REST (using of simple HTTP Verbs (get, post, delete etc...), but that's not the main point here...
I think I understand the main goal of the REST Architecture and tried to make a little concept with an URI and Verb Mapping. Here just a simple example of the mapping:
/location/{location_id}/product
/location/{location_id}/product/{product_id}
Both are GET operations who should get me ether a single product or all products of a location.
How would a simple PHP REST Web Server look like with these functions?
Another part should implement a User Authentication from the iPhone. Somehow i need to store the user session, right now I don't have any idea how to make that. The goald is that if only a user is logged in, he could review the product.
Now I've researched also the Web but couldn't find an easy step-by-step Tutorial.
Do you know any good Tutorials which will help me achieve my goal? :)
A lot of people prefer using PHP Frameworks like ZEND. This seems very interesting, but it seems like a big package with a lot of modules.
Does someone know exactly which Modules are needed to get my Web Service working?
This is quite a good tutorial, it uses the codeigniter framework which makes the learning curve a bit steeper but makes it a lot more powerful in the long run.
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
If you want to build this the custom way it's actually very easy to do if you want to return information in the JSON format especially for php5 which is generally well supported amongst hosts these days.
Essentially the steps are like this:
Pass in product id via url and retrieve using GET i.e. service.php?product_id=10
Query database and return data for product id that was passed in
Store returned data in an array
Set header content-type to application/json
json_encode the result (json_encode)
That way when you call that url in a browser you will get a nice JSON formatted array result in a key:value pair manner. And as of iOS5 json parser comes with the framework (for earlier versions SBJson is a good framework to use (SB JSON))
I am a beginner with PHP but I know most of the basics. I currently have an API for my website, coded myself, of which I can call different methods with different parameters and they will scour my databases for the relevant information.
However I want to convert it to REST.
So instead of having requests like this http://mywebsite.com/api/?param=allPosts I would have something like http://mywebsite.com/api/posts/. I would do this for each of my 23 different params.
How could I do this?
One way would be to use a micro framework for routing. This would 'point' url request patterns to relevant php files (controllers) to manage those requests and serve content (or perform CRUD operations, or whatever it is your API does).
There's a good post here with some discussion and further links.
https://stackoverflow.com/questions/115629/simplest-php-routing-framework
I'm currently in the process of using the framework Silex for this exact purpose
http://silex-project.org/
It may be that you wish to convert your PHP application to use one of the many frameworks out there (which will handle routing amongst other things).
The usual suspects are
CakePHP
Codeigniter
Symfony
Lithium
and there are many more...
This is not strictly speaking RESTful that is just prettifying your URL's.
To "Prettify" your URL's you could implement something like this:
Trim your base URL of the start of the request
explode the remaining string by the "/" component
The first component (normally) is related to your controller
The next component is your action in this case equivalent to how your using ?param=allPosts
RESTful routing is based around the idea of using the different HTTP verbs (GET/POST/PUT/DELETE) to decide what actions to take on your resources on the server. Wikipedia has a good overview.
One way would be to use apache's mod_rewrite to effectively convert the second type of request to the first. It's not necessarily ideal, but it's a pretty straightforward solution to your problem.
I have an existing website written in PHP. I would like to add a REST API. I like how easy creating a RESTful API was using Django. Are there any CONS for using Django for the sole purpose of creating an API on a PHP powered website? Thanks in advance.
There are a couple of cons:
your codebase will be larger
every change in the data model on one side must be done on the other side aswell
it will require more resources from your server
you have 2 systems to maintain
But for the rest, I can see why it would be easier to do this with Django than it would be to do with a plain PHP API. I have my doubts that there are no PHP libraries available to do something similar though.
I love Django, but I'm not sure that it would benefit you here. Maybe I don't completely understand how you plan to use it, but it seems like if you already have your data access and logic done in PHP then you would have to re-code that in Python in order to leverage Django.
If what you really want is clean urls and simple url mapping then you could probably use CodeIgniter or CakePHP. That way you don't need to rewrite your existing code in Python or having the same code in 2 different languages.
I've been asked to help a friend's company to bring up a web application. I have very limited time and I reluctantly accepted the request, at one condition. As most of the logic goes on in the back-end, I suggested that I would finish the complete back-end only, allowing a front-end developer to simply interface with my backend.
I plan to do the back-end in Java EE or Python (with Pylons). It does not really matter at this point. I plan to have my back-end completely ready and unit-tested, so that my input will hardly be needed after my work is done.
I know they have a PHP programmer, but as far as I could tell he is a real rookie. I want him to basically interface with my backend's services in the easiest possible way, with no way of him "stuffing" it up. It's basically a CRUD-only application.
I could implement the backend as accessible through a webservice such as XML-RPC or SOAP. Even a RESTful API could be possible.
However, my main objective is to make something that complete "noob" PHP programmer can easily interface with without getting confused. Preferably I do not even want to talk to him because I generally have an extremely busy schedule, and doing "support calls" is not something I am willing to do. Which approach should I choose? I would welcome any suggestions and inputs!
I would personally choose a REST API, probably with a JSON response. SOAP and XML can be a bit heavy-handed for simple services, and even the most novice web developer understands the concept of accessing a basic URL, even if they don't grok the overall concept of REST. There are myriads of ways to work with URLs in PHP, so I'm sure they'd be able to come up with something, even if it was a hack job instead of a nice client package.
I would also likely choose JSON encoding and decoding, as it's generally fairly straightforward, while XML parsing can be a bit more daunting.
I would also write up at least some basic documentation on the service, no matter what formats you choose. Otherwise there's no way you will escape support calls. Your target consumer must have a reference of the remote actions available to him, or a method to discover those actions. It would probably take you 10 minutes to whip up some example code when it's ready, and those 10 minutes could save you a lot of emailing.
Definitly go with a rest-like implementation, and return query string formatted output.
Just remember that php will turn array like variables into an array on the php side.
Take a query string for your parameters
Input:
p1=v1&p2=v2....
Output:
output1=var1&output[0]=var2;output[2]=var3
Accessing this in php is then a simple as
<?
$request['myparam1'] = param;
...
$webService ="http://path.to.service?".http_build_query($request);
parse_str(file_get_contents($webService),$response);
// response is now an array with you response parameters in it
// $response['responseParam1'], reponse['responseParam1'] etc
?>
parse_str
http_build_query
Been there, done that.
Backend in Django, frontend in PHP by a 'we do pages' contractor. i whipped up a REST-like API using JSON, provided them with a couple of 5-line PHP functions to access my service as a key-value store.
After a couple of false starts (where they tried a contrived and redirections scheme instead of using the functions i sent them), they got it and everything went smoothly after that.