PHP API Development - php

I am planning to write an API using PHP and and I am very interested in HTTP protocol type of API that exists but I don't know what people call that type of API. I think you can point me towards the best guide if I let you know how I want the developers to use it.
Assuming there are following functions.
Login
SignUp
GetRequests
Now the Login should take 2 parameters Username and Password of the user that exist in the database. It should then return a token which will be used to request other resources like "GetRequests" function. So once the user has the token, s/he can call "GetRequests" passing the token and will get the information.
The SignUp function works the same way as login but the input parameters are different. It also returns a token and can be used to make other requests for resources.
There are many other functions but I believe these are enough to get an idea of what type of API I am talking about. Can you please guide me as which Tools or Frameworks I can use to develop this sort of API quickly and easily.

You don't need any specific tools or frameworks to write such a thing or to put it another way, you can use any framework you want. A typical web API "function" works just like an ordinary web page, the only difference is that is doesn't accept cookies (and other browser-specific http headers) and usually returns its output as xml or json rather than html.

What you are describing is a general implementation pattern, and isn't specific to any single approach of implementing web services.
Nowadays, many web service API's are implemented either using REST or SOAP. You would be able to implement what you are describing with either of these.
You can get a technical overview through the above Wikipedia links, or, simply google REST vs. SOAP, and you'll get lots of pages giving you the good and the bad of both approaches.

My advice would be to Learn REST, JSON. I think this tutorial Working with RESTful Services in CodeIgniter might be interesting to study.

maybe something like this ?
$command = $_REQUEST['command'];
$param = $_REQUEST['param'];
echo api::$command($param);
class api{
static function saySomething($param){
return $param;
}
}
and try access the page with
http://localhost/test.php?command=SaySomething&param=what

Related

RESTful Api or direct access?

I'm asking this question because some of the websites is visited seems to be using a RESTful API to access the data even if it's on the website...
For example: my website will have 6 pages and 5 of them use the DB. But, I will also have a REST api for my partners...
So, the question is:
On my website, is it better to access directly the DB via mysqli_query or to use a RESTful API with Ajax calls to load data?
Just a note: I'll be using Zend Framework 2 for my RESTful API except if someone has a better option... I know Node.js and PHP... I'm able to write it in Ruby or something if it's better for me... Need a opinion on that...
Use the RESTful API.
The specification of REST is that we use the HTTP methods, which he calls verbs.(GET, POST, PUT, DELETE).
A direct request would be limiting it, or you would be using at most two method (verbs) - GET and POST.
For that you have to do this:
GET /user/frederick/edit
GET /user/frederick/update
GET /user/frederick/delete
GET /user/new
And with a RESTful API:
GET /user/frederick/
POST /user/new/
PUT /user/frederick/
DELETE /user/frederick/
The advantage of using your own API is that you don't have to write duplicate code. For example, you might have generate_for_rest and generate_for_server functions that do the same thing and just emit data in different formats. It's a good idea to reuse your own APIs as much as you can.
That said, I do find it a bit unusual that a website would communicate to itself with its own RESTful API. That requires an HTTP request (though it should be extremely fast) and conversion of the data twice. Instead it would make more sense to have an API that generates the data that you need and a facade that converts that data into formats for it to be used.
For example you could have a function get_all_users. Internally you can use get_all_users to get the results as php data structures that you can use immediately. In your controller that responds to HTTP requests you may do a JSON conversion, but you shouldn't be doing any duplicate work to get the data for either internal or external use.

Developing embedded js/maps library extended from gmaps

I currently have a web app that uses the google maps API, PHP, and MySQL to populate custom map bubbles and markers on a map.
Currently, the app is hosted by us and managed by us and is included as an iframe on a clients page, however this is quite tiresome..
I would like to develop an API/library that can be included on the page and then inject code into a div container (much like Google maps does). However, i have no idea what to search for or what to read up on to learn.
I have a basic rest api that is configured to provide read-only functionality in json/jsonp format to an authorized client. I am using Phil Sturgeon's REST-SERVER library for CI.
Here is a link to the current format, we pull this page in an iframe with no-scrollbars.
http://fhaz.mapitusa.com
Update: I found a partial solution.. web widgets: http://alexmarandon.com/articles/web_widget_jquery/
i need to develop a web widget.
I need to know:
what to learn
what types of programming methodologies to know
What to look for examples
What are some options to get away from the iframe and using a sort of "hard embed".
You didn't say it out loud, but because you specifically mention you now have a read-only api i figure you also want to send commands to the (your) server. I would start with looking into authentication methods. And for this, I would go for OAuth. You'll have to write a basic client class which can connect and authenticate the client to the server. This can be pretty simple and small. Php even has a pecl extension available (see http://nl.php.net/manual/en/book.oauth.php) which is pretty easy to use. If you do not have the possibility of installing pecl extensions curl will also do the trick, and even that isn't really necessary. Twitter also has a nice explanation of how OAuth works, with links to external resources. Check it out! https://dev.twitter.com/docs/auth/oauth
Note that at the server level you'll have to implement your own role system, oauth only lets your client connect to the server in a secure manner. Ie. it will let your "users" log in to your application, but will not check if the logged in user is, example given, an admin user with all rights, a read-only user or something in the middle.
If you have OAuth straightened out just write a list of API calls you want to implement. You should namespace them, for example like:
/map/marker/get
/map/marker/set
/map/bubble/get
...
Your client API should be able to make a call like this:
$api = new MyGreatApi();
$params = array('id' => 3, 'color' => 'red', ...);
$response = $api->call('/map/marker/get', $params);
echo $response;
Check out some oauth library implementations like the one Twitter promotes (https://dev.twitter.com/docs/twitter-libraries#php), or in example the really simple one bits on the run uses (http://developer.longtailvideo.com/botr/downloads/php-api-kit.zip)
At server level you catch the api call and route the request to the specific controller (to use some MVC terms). If, eg, you fetch the call '/map/marker/get' you can just explode('/', $call); and search for the right class/function/method/whatever and let it do the magic for you, then send back the output (which can be as simple as to echo $output) and you are up and running! Note that if you have the authentication and role-checking right, the functions which produce the output can be treated as normal, oldschool, php functions. There's nothing special at them! It's the authentication and routing of api calls which should be your main concern.
I hope this clarifies some of your questions and give you a direction. If I misunderstood your question, please correct me!

PHP RESTful Web Service for an iPhone

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))

how to create an account api for my site

i want to create an api for my sites so that i allow other web developers to integrete my api for their user login and signup ..... how can i do that...
This is an extremely broad question, so here's a broad answer: You make a page that takes arguments and outputs the answer in an easily-parsed format (JSON, XML, etc.)
For example: http://example.com/api?action=list_users could return:
<user>
<userid>1</userid>
<username>foo</username>
</user>
Create a way for developers to query your server, like Michael said. A common technology for this is called SOAP and another (simpler) is called REST, but you can of course use other formats if you wish.
The most important thing is that you document the API so other developers knows exactly how it works. Write down every detail about the API: how it works, which methods it provides and which arguments are mandatory and optional. Ideally you also provide examples or even a fully functioning client implementation.
Maybe I'm misunderstanding the question, but integration of login systems sounds like OpenID to me. Why make your own protocol when you can build to a standard one?
I personally prefer to use an MVC Framework to create an API as the structure for me is just right!
By using a system like CI (CodeIgniter) you can create a library for authentication.
This being said with the MVC Model you can use like so
http://example.com/api/users/latest/
http://example.com/api/users/id/33/
http://example.com/api/users/id/33/
The within your library just build the authentication process so you can quickly check permissions for different entites.
Example in PHP and CI
users > latest
class Controller_users extend CI_Controller
{
public function latest($limit = 10)
{
if($this->library->authorized(API_AUTH_LATEST))
{
//show the data.
}
}
}
The authorized function will automatically read the headers / for the API Key etc and trigger error output.
This to me is a simple way for an API to be achieved cutting out a lot of crap from SOAP.

Easiest RPC client method in PHP

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.

Categories