How to write a REST API? - php

I'm writing an iPhone app as a hobby project and it will need a web service to provide it with data. It's not very different from what I do at work, but at work I only write views and controllers. Someone else is responsible for writing the model and usually the clients provide the web service.
I have done some web programming before, back when everyone were using MySQL and PHP, so my skills are a bit outdated, but I'm confident that I would be able to pull it of using the techniques I already know. However, I don't want to waste my time using obsolete tools. I've figured out that the state of the art would be to write a REST API. I was thinking that there should be some pretty good frameworks out there that pretty much just gives you a REST API with CRUD functionality as soon as you've defined a model.
I guess my question is: What would be the fastest way to get a REST API up and running? I really just want to focus on writing the iPhone app and not spend too much time on this API. It would be great if I could get web administration and revision history too. I should also add that the API isn't supposed to be public, so support for authentication would be great as well.
Just to be clear. I wouldn't mind a PHP framework. In fact it could possibly be better since I know that my current hosting supports it.

EDIT:
The links below which apparently were good for 3 years are no longer working so I went and found a couple of new tutorials that I think are going to stick around for a while. These are on the Ray Wenderlich site, a very well respected ios dev tutorial site. The first article actually references the broken links below but it is complete within itself:
How To Write A Simple PHP/MySQL Web Service for an iOS App
and the second one has a little twist to it. It used parse.com on the backend and AFNetworking. Both of which are quite excellent.
How To Synchronize Core Data with a Web Service – Part 1
I have fixed the broken links below by finding the articles in the way back machine. People seem to like the links so I will keep them. The links above should provide more food for thought.
I am doing exactly the same thing with my iphone app. I found this article on building a RESTful API in PHP:
https://web.archive.org/web/20130910164802/http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
and there is also a followup article here:
https://web.archive.org/web/20130323001500/http://www.gen-x-design.com/archives/making-restful-requests-in-php/
with a link to source code at the bottom of the article.

I have programmed a REST API in ZEND Framework using the Zend_Rest_Controller, on the iPhone I used ASIHTTPRequest. My experience with both where good. At the beginning I had some trouble setting up ZEND and connecting it to mySQL, but once I figured out how to do it I was able to write the API very quickly. I can share more information with you if you have any further questions.
EDIT: There seems to be no official documentation on Zend_Rest_Controller. This link describes how to use it to create your API. You simply have to disable rendering in the init() of your subclass and implement the methods for each REST call.

Just to let you know:
I ended up using Ruby on Rails.
EDIT: Since this answer has been downvoted for not providing the reason behind choosing Ruby on Rails and also no instructions on how to write a REST API with it, I thought I would give you my motivation and some simple instructions.
I started reading a book about Ruby on Rails and realized that all I needed to do was to use scaffolding and I got a JSON REST API for free.
Here's a good guide to get you started: http://guides.rubyonrails.org/getting_started.html
When you have your Ruby on Rails environment up and running, creating your REST API isn't harder than running:
$ rails generate scaffold Post name:string title:string content:text
(Example from the above link.) I also found that Rails is very easy and free to deploy to heroku, which meant that I didn't have to pay for hosting for my very basic, low traffic, REST API. There are many other reasons why I am very happy to work with Ruby on Rails, but that's beyond the context of this question.

I followed a quite simple tutorial for creating RESTful APIs with PHP:
Corey Maynard - Creating a RESTful API with PHP
The main concept includes:
one abstract class that handles the parsing of the URI and returning the response, and
one concrete class that consists of just the endpoints for the API.

What about Python?
I'd use Python, Django and Piston.
I'd generate Django models from your
existent DB using inspectdb.
Add the Django admin to your models.
Add Django Piston to your app.
Profit.
With no experience with Python or Django probably it'll take you a day to develop this solution and all code is unit tested and proved to work.

If you want to use PHP I recommend using the CodeIgniter framework with Phil Sturgeon's REST server:
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2
https://github.com/philsturgeon/codeigniter-restserver

Checkout the following PHP class that follows MVC.
http://www.phpclasses.org/package/5080-PHP-Implement-REST-Web-services-servers.html
Hope this helps.

If you already know PHP, there's nothing wrong with a PHP/MySQL backend. You can send all responses in iPhone-compatible plist xml format, and instantly turn the response into a NSDictionary/NSArray/NSNumber data structure with this short snippet of code:
NSString *response = [request responseString];
NSData* plistData = [response dataUsingEncoding:NSUTF8StringEncoding];
NSPropertyListFormat format;
NSString *errorStr;
NSDictionary* plist = [NSPropertyListSerialization propertyListFromData:plistData
mutabilityOption:NSPropertyListImmutable
format:&format
errorDescription:&errorStr];
I also use the ASIHTTP package for forming URLs, sending asynchronous requets, and receiving the responses, I highly recommend it:
http://allseeing-i.com/ASIHTTPRequest/

You should use whatever languages you are comfortable with for the web service. Any language that can formulate REST responses to requests is fine.
That said, if you want to get something running quickly, I suggest using Python on Google App Engine. It's free and you can use Java instead of Python if you so desire. App Engine supports authentication using OpenID and/or Google Accounts (not sure if they're mutually exclusive) so that should make things easier to code.
As far as making the requests on the iOS device, I suggest using ASIHTTPRequest.

Another option is restSQL, an ultra-lightweight persistence framework. See http://restsql.org. It supports MySQL and PostgreSQL and runs in a standard Java EE container, e.g. Apache Tomcat.
restSQL is a very unconventional data access layer. restSQL is not an object-oriented view of the database. It presents flat or hierarchical "views" of relational database tables. These views are query-able and updatable through a simple REST-based HTTP or Java API. The HTTP interface is based on REST principles, which use HTTP’s built-in features, rather than abstracting away from them.
You want a 'REST API with CRUD functionality' and that's exactly restSQL's sweet spot. You could do this with no code. Simply define your SQL Resources via XML files and start doing HTTP calls against them with full CRUD capability.

Related

Using ExtJS4 + PHP with RESTful web services

I want to build an app using ExtJS 4 and PHP.
I will follow the MVC pattern with ExtJS 4.
However, I want to use RESTful webservices with PHP.
Yet I am not sure how to proceed.
How can I call for Web Services that are PHP functions?
How am I going to give the directory like structure to my links?
You can obviously use Ext.Ajax.request() to craft any RESTful URls that you want. However, be sure to check out the REST proxy that's built into Ext JS's data package. By connecting this to your store/model, you can dynamically generate RESTful URLs which can be used for the vast majority of your generic CRUD operations.
RE: the PHP side, that's a big question. Fortunately, there are literally a billion turtorials on creating RESTful services in PHP, so I'd dust off your Google-fu and start there. Here's a very simple introduction that just happens to use PHP: http://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest--net-16340
You are most likely looking for Ext.Ajax.request.
There are some examples of Ext.Ajax.request from this stack overflow article.

Should I be writing tests for a rest api wrapper?

I'm very new to the whole testing scene. I've been reading about BDD testing (in my case I'm writing PHP applications, so I was researching Behat as a BDD framework) and I find it very interesting.
I've searched online for some information on bdd testing for api wrappers, but I found a lot of different results.
I'm going to write an application for a service with a REST api. But I also need to write the PHP api wrapper. So my question is, should I be writing tests for the wrapper and what kind of tests shoud I be writing?
A BDD framework could work but it might prove to be fragile considering the possibilities of what might happen between selenium, your app using the api, and whats going on inside your api.
There is a great php way of doing this
http://docs.guzzlephp.org/en/latest/
If you like other languages you could use Mule ESB to do testing against web service api. I have found it to be very good at running custom anything against a service or anything http. If you like groovy or java Mule ESB is perfect for getting directly at an endpoint to pull the reponse apart and fire off valid and invalid requests. It has a pointy clicky interface for a large variety of possibilities. If your api returns xml you have plenty of ways to parse it directly. It works well with JSON too. Even if you created your own format for the data response you can just dig into that fairly easily. Guzzle gives you much of the same but in a php curl friendly way but no pointy clicky stuff.
If your language and framework you are using for your REST api has a decent unit testing package then do that too especially where it makes sense. I know you are using php and I hate unit testing in php but sometimes you can't do it any other way to verify certain methods are correct when you want to protect certain methods.
I have seen successful api test suites created using a javascript testing framework like Jasmine or qUnit as well.
It all depends on what you are comfortable with and nature of what is going on with your api and what features of your api you would consider are important to cover.

Connect appengine with cakephp

I'm thinking in create a webapplication with cakephp but consuming python's appengine webservice. But, to install cakephp etc, I need to configure the database. Appengine uses another kind of datastorage, with is different from mysql, etc.
I was thinking in store the data in appengine, and using the python webservices, and with the cakephp application comunicating with the webservice, for insert and retrieve data.
Is there any good resource for this, or is it unpossible.
Obs: also opened for a possibility for developing the webapplicaiton completely in python running in appengine. If anyone has a good resource.
Thanks.
I think that you should try different solution: http://aws.amazon.com/simpledb/
It appears that CakePHP is a MVC framework that's very similar to django, which is included in app engine for python. I'm not sure why you would want to store your data in google app engine, unless you're dealing with an extremely large amount of data, in which case you're likely comfortable enough working in python to just make the app work entirely on GAE.
See the official docs for more info:
http://code.google.com/appengine/docs/python/overview.html
http://code.google.com/appengine/articles/django.html
What you can do is run your CakePHP app on a standard LAMP web host and access the GAE Data Store through a REST or RPC web service. This isn't such a bad idea if you already have a CakePHP front-end that deals with RPCs in the backend, but if your Cake app stores all it's Models in MySQL it could take considerable effort to adapt it.CakePHP Models abstract their storage method using the DataSource class. You might be able to find a DataSource class that uses REST or RPC. However, if you don't have a very considerable investment in CakePHP Controllers and Templates I would suggest simply building your app entirely in GAE
You can not run PHP on GAE. If you run PHP somewhere, it is a bad architecture to go over the internet for your data. It will be slooooow and a nightmare to develop in.
You should store your data where you run your php, unless you must have a distributed, globally scaling architecture, which afaiu not the case.
There's a detailed tutorial on getting CakePHP up using the PHP runtime that Google recently announced. http://aymanrb.blogspot.com/2013/05/cakephp-deployment-on-google-app-engine.html

Building a REST API quickly from a Database model

I've designed my database diagram(11 entites) for my prototype application. I need to have an REST API on top of this that will allow me to build a prototype android tablet application that talks to it.
Considering this is only for prototype purposes. What would be the quickest way to get a API up and running that would allow me to get, put, delete etc..
Security at this point isn't an issue so even if all add edit delete were open that would be fine.
My initial idea is to build this with PHP and MySQL maybe using the Yii framework to help but I feel there might be something that might be faster for my purpose.
Any thoughts or recommendations or advice?
It is worth looking into API rapid-prototyping tools like Apify (tutorial) since you're starting from scratch. If you're planning to have both an API and a Web site accessing the same data, consider using one framework for both as it helps prevent duplicating logic. CakePHP and Yii are good examples of multipurpose frameworks that are suited for this type of development.
If Python is an option, it is trivial to use a light-weight http framework to build a REST API that accesses a database.
Here's a snippet for a fully functioning http server using the itty framework: https://github.com/toastdriven/itty/blob/master/examples/web_service.py and https://github.com/toastdriven/itty/blob/master/examples/posting_data.py
Look at this project which allows you to create an API REST in seconds.
https://github.com/GeekyTheory/Automatic-API-REST
Features
Creation a powerful API REST of your MySQL Data Base in Seconds.
Management of the API in situ, it is not neccesary an extra data base.
Private tables and fields.
Custom queries.
Installation
Clone the repo.
git clone https://github.com/GeekyTheory/Automatic-API-REST/
Place it in your web folder /var/www/YourWebPage/
Open the file config.php and complete all the fields with the server credencials.
Go to domain.com/AutomaticaApiRest

Best way to implement a Rest API with PHP on WAMP web server

I own a web server running Windows (WAMP). I want to know the best way to implement a Rest API (a very simple one) in order to let a user do something.
Diagram flow:
alt text http://img215.imageshack.us/img215/6105/flowe.png
I have programming skills, in fact, I developed a web server in VB6 who process the queries and when it finds the command (http:/serverIP/webform.php?cmd=run&item=any) it does something, but I really want to develop a solution using the WAMP server.
Some people consider the solution of executing a exe when a command is detected a bad solution for security issues, but this specific project I have is for the use by some people (trusted people) who dont have intentions of hacking the server.
So, what do you think?
Remember:
Its not a public API, its for some people and some programs who will use
the API
Its a very simple one, only one command using POST or GET.
Thanks
Ive just recently finished a REST API project on PHP and it was a good experience. The way I see it, the fastest/easiest way to implement this is using the following elements:
Object Oriented PHP
MVC paradigm
Create a request dispatcher
I found this link very useful when I started, it should get you going in no time:
http://particletree.com/features/how-to-add-an-api-to-your-web-service/
Edit:
I didnt use this framework but it looked promising: http://tonic.sourceforge.net/
Also, CakePHP supports Rest and is a neat MVC framework. If you're looking to implement in no time, go with CakePHP.
Good luck!

Categories