开发者

Create a REST API From a PHP API

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/开发者_StackOverflowapi/?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:

  1. Trim your base URL of the start of the request
  2. explode the remaining string by the "/" component
  3. The first component (normally) is related to your controller
  4. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜