Create a REST API From a PHP API - php

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.

Related

Versioning a PHP Lithium API

Goal
I've been tasked with versioning a pretty large PHP Lithium API.
The end result I'm looking for is to use namespacing to separate the versions.
For example, normally a lithium route that looked like this:
Router::connect('/{:controller}/{:action}/{:id:\d+}');
Could have the following URL, map to the following PHP call:
http://www.fungames.com/game/view/2
app\controllers\Game::View($gameId)
But I would like to create the following mapping:
Router::connect('/{:version}/{:controller}/{:action}/{:id:\d+}');
Such that the following two calls could be made:
http://www.fungames.com/v1/game/view/2
app\controllers\v1\Game::View($gameId)
http://www.fungames.com/v2/game/view/2
app\controllers\v2\Game::View($gameId)
Problem
Unfortunately, the Lithium documentation doesn't make much mention of API versioning. There's a brief mention here as an example of continuation routes. But that approach would required making if statements in my controllers to version my API, and I personally consider that a poor approach.
TLDR
What is the best way to achieved namespaced API versioning when using the PHP Lithium Framework?
API versioning is a really broad topic, and while Li3 gives you all the necessary tools to implement any approach you choose, the actual implementation is up to you. Having said that, the routing layer is fairly sophisticated and will get you very, very far. See this gist on routing configuration examples.
Combining this with Request::get() which allows you to match on any request parameters including headers (you can pass get()-compatible values as $params in Router::connect() — see examples here),
and Request::detect(), which allows you to implement custom matching logic, you can send any configuration of values down to the controller/dispatch layer. This allows you to segment your versions by differently namespaced controllers (with fallback to the default), prefixed actions, or pass a namespace/class path for a different model.
Yet another approach, and one that I would recommend in the general case, is implementing a set of transaction managers/mappers for any endpoints that need to be versioned, and using them as an intermediary between your controller and your model, then use routing to switch between them.
This approach is made easier if you evolve your API using, i.e. content types, since you can choose a mapper based on that. This is also nice since version numbers are strongly discouraged by REST's creator.
Anyway, hope that helps.

How to create a RESTful API in php

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.

Routing REST requests without framework?

I have been reading the article to learn how to build a rest API:
http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
At one point it says "Assuming you’ve routed your request to the correct controller for users"
How can I do this without a framework?
I am writing a REST API that I can interact with from a different application. I ready the tutorial above, and it makes sense mostly, but I don't exactly understand what it means to route my request to the correct controller for users.
Assuming you are using Apache, you can accomplish this easily using a combination of mod_rewrite and some PHP-based logic. For example, in your .htaccess or vhost definition, you could route all requests through a single handler, possibly index.php:
# Don't rewrite requests for e.g. assets
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*+)$ index.php?q=$1 [L]
...then in your index.php file do something like:
$target = $_REQUEST['q'];
/* parse the request and include the appropriate controller PHP */
For example, a request for /products/1234 might result in a controllers/products.php handler being included. That handler could then act on product 1234. Because you're using REST, you shouldn't need to be concerned with the original request having a query string parameter.
There are multiple ways to accomplish what it sounds like you're trying to do, this is just one of them. Ultimately what you go with will depend on what your specific requirements dictate. The above pattern is fairly common however, many frameworks use it or something like it.
I think this is a matter of terminology. Every code with some level of generalization can be called "framework". And since you're asking about "routing", which provides a starting level of generalization, every implementation becomes a framework.
If you don't want to use existing fully-fledged frameworks, you can elaborate your own light-weight-implementation. Here is some articles to start:
Write your own PHP MVC framework
PHP MVC framework in one hour
(the author has decided to remove this post because he thinks that using a modern fully-fledged framework is more appropriate way of programming such things, yet some people find such simple and stripped-down approache more suitable in many aspects: learning, efficiency, no huge dependencies, etc); the post is available on some other sites, for example, in the wayback machine or copies
The Model View Controller in PHP
All these intros include explanations of the routing mechanizm and demonstrate its implementation.
Basically, a router is a kind of internal "DNS" (in a figurative sense) inside your application. When a request arrives to your site, you need to dispatch it to appropriate worker class, according to that request properties. This is the router's task.

Zend Framework – subdirectories and deprecating action within the URL

I’m in the process of learning to use the Zend Framework, and I’m therefore trying to grasp the concept of MVC. Through the Zend manual, and a very helpful Youtube video tutorial I have sort of understood the concept – still there are some things I need to clarify.
The web project I’m currently working on is a web site for an organization I’m a part of. It consists of:
The public portion, mainly consisting of information about us, a calendar and some media – mostly static information, but a couple of pages, like the calendar, will need to retrieve some data from the DB.
The internal pages, which after a login will allow users to RSVP to events and comment them as well.
The administrative controls , allows the admins to add events and manage users etc.
So far it looks like Zend wants the URL to look like this:
http?://[domain]/[controller]/[action]
So here are my questions:
Do I always have to have an action in the url, or will the lack of an action use the index-action as default?
Can I have a subdirectory to distinguish between the internal and public portions of the site: http://[domain]/internal/[controller]/[action] ?
Can this be done simply by having a subfolder within the different MVC-folders somehow?
The latter question isn’t really that important, but I’d like to separate the two portions of the site somehow.
Do I always have to have an action in the url, or will the lack of an action use the index-action as default?
A controller can have a default action which is triggered when no action is specified in the URL. Look for default action or index action.
Can I have a subdirectory to distinguish between the internal and public portions of the site: http://[domain]/internal/[controller]/[action] ?
Yes you can have, but I assume subdirectory refers to your URL, not to the actual file-layout on the server. You can do so by just having a controller per "subdirectory".
Can this be done simply by having a subfolder within the different MVC-folders somehow? The latter question isn’t really that important, but I’d like to separate the two portions of the site somehow.
You can separate per controller and you can even separate with modules. As far as I know of modules in zend-framework, this will all be in it's own sudirectory per module.
I think you're especially looking for Using a Conventional Modular Directory Structure.
The questions you are asking are in the area of routing which generally means: Given a URL on which the HTTP request is being made:
Which controller should be instantiated?
Which action on that controller should be run?
What parameters should be passed to the action?
The routing docs in the ZF Manual explain how routing works by default and how you can specify your own routing. But looking at them now, I don't think they do a great job of introducing the subject matter for a first time user. This post might be better, though it is only a single, simple example.

General Web Programming/designing Question:?

I have been in web programming for 2 years (Self taught - a biology researcher by profession). I designed a small wiki with needed functionalities and a scientific RTE - ofcourse lot is expected. I used mootools framework
and AJAX extensively.
I was always curious when ever I saw the query strings passed from URL. Long encrypted query string directly getting passed to the server. Especially Google's design is such. I think this is the start of providing a Web Service to a client - I guess.
Now, my question is : is this a special, highly professional, efficient / advanced web design technique to communicate queries via the URL ?
I always felt that direct URL based communication is faster. I tried my bit and could send a query through the URL directly. here is the link: http://sgwiki.sdsc.edu/getSGMPage.php?8
By this , the client can directly link to the desired page instead of searching and / or can automate. There are many possibilities.
The next request: Can I be pointed to such technique of web programming?
oops: I am sorry, If I have not been able to convey my request clearly.
Prasad.
I think this is the start of providing
a Web Service to a client - I guess.
No not really, although it can be. Its used to have a central entry point to the entire application. Its a common practice and has all kinds of benefits, but its obviously not required. Often thes days though even a normal url you see may not actual be a physical page in the application.. each part of the path may actuall be mapped to a variable through rewriting and routing on the server side. For example the URL of this question:
http://stackoverflow.com/questions/2557535/general-web-programming-designing-question
Might map to something like
http://stackoverflow.com/index.php?module=questions&action=view&question=2557535&title=general-web-programming-designing-question
is this a special, highly
professional, efficient / advanced web
design technique to communicate
queries via the URL ?
Having a centralized page through which all functions within an application are accessed is part of the Front Controller Pattern - a common pattern in applications generally used as part of the overall Model, View, Controller (MVC) pattern. In MVC, the concerns of the application are divided into the model which holds the business logic. These models are then used by the controller to perform a set of tasks which can produce output. This output is then rendered to the client (browser, window manager, etc..) via the view layer.
I think that essentially what you are asking about is query strings. In a url after a page, there may be a question mark after which, there may be URL parameters (generally called GET request parameters.)
http://www.google.com/search?q=URL+parameter
Generally, processing this would be done on the server-side. For example, in PHP, one could use the following:
$_GET['q']
The aforementioned code would be the value of the variable. Alternatively, to do this client-side, one could use anchors. Replace the question mark with a hash sign #
Since this is used for anchors, when a URL is changed to have an anchor tag, the page is not refreshed. This allows for a completely AJAX-driven page to manipulate the URL without refreshing. This method is often used also for enabling back-button support for AJAX pages.
In JavaScript, one can use the onload handler as an opportunity to read the URL of the page and get the hash part of the URL. The page could then make a request back to the server to read any neccessary data.
It's a consequence of using a front controller architecture. This fits neatly with the idea of a wiki where the same code is used to render multiple different wiki pages - the content is defined by the data.
Using the query part of the URL for the page selection criteria is not the only solution. e.g. if you are using apache then you could implement:
http://sgwiki.sdsc.edu/getSGMPage.php?8
as
http://sgwiki.sdsc.edu/getSGMPage.php/8
(you'll need to add your own parsing to get the value out.
Alternatively, you can use mod_rewrite to map components out of the path back into the query.
There's no particular functional/performance reason for adopting any of these strategies. Although it is recommended, where the URL is idempotent, that each page be addressable via a GET operation (also useful for SEO).
C.

Categories