how to create an account api for my site - php

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.

Related

Universal structure or service for API to API Conversion

As part of an App i'm developing there's a requirement to create a conversion between our RESTful JSON API and a number of other formats. The intention is to allow output from our API to be converted to make further requests to API's that use different formats such as SOAP, or other REST based API's with different requirements.
A few examples of the kind of things I think this might need to do:
manipulate the JSON output to use different keys (and maybe only a subset of
data
convert to an XML packet/document
convert to a valid SOAP request
output data as a specific filetype/structure (such as csv)
I'm interested really in what approaches should I be looking at here. It would seem to me that this should be a fairly common request so i'm interested if there are specific libraries I should look at, or existing services perhaps. If such a service doesn't exist then ideally I want to create a common structure whereby the 2 disparate services can be mapped using a universal set of tools that are just then configured to work together. This will be within a Laravel PHP application so any Composer compatible library would work.
Following on from my comment:
"I am not aware of any such library to do this, but as a rough guide I think you probably want to create some kind of adapters which all use a common interface. These adapters can then be written to deal with the conversion you are trying to achieve via some open-source library. Manipulating the output might be a good excuse to use the decorator pattern :) Sorry I could not be of much more help."
An example of what I think you are after is the following:
An interface for your adapters
interface DataConvertor
{
public function convert(DataInterface $data);
}
An interface for the data you are passing around (the data will be an object also with a common interface to work from).
interface DataInterface
{
/**
* returns a json string
*/
public function asJson();
}
Then you can create your adapter for use with some 3rd party library.
class SomeThirdPartyNameAdapter implements DataConvertor
{
public function convert($data)
{
//some logic here to make my data object with a known asJon method
//suitable for use for some 3rd party library, and use that library.
$rawJson = $data->asJson();
//manipulate this as needed ($compatibleData)
$thirdPartyLib = new ThirdPartyLib();
return $thirdPartyLib->thirdPartyMethod($compatibleData);
}
}
Obviously this is just a rough guide and there may be other parts of this you can make abstract (e.g. have the adapters implement the DataConvertor interface but also extend some abstract class to inherit some functionality, or other method to add to your interface).
Hope this helps
Carl is right that a great approach is to create some adapters using a common interface. Then you can provide implementations that convert JSON to XML or JSON to a CSV, etc.
However I would strongly recommend looking into Mule ESB as a solution as well. http://www.mulesoft.org/
It's a Java based, open source project that allows you to do pretty quick and efficient integrations. For example, you could create a "flow" (a Mule term) that makes a RESTful call and then converts the data and pumps it out to a specific destination (CSV, SOAP call, XML, etc.)
The real selling points of Mule (things that have worked great for me):
Very easy to deploy. It works similar to something like Tomcat, where you can deploy a package and it runs on a server.
Tons and tons and tons of boilerplate code already done for you.
Free and stable. They have tons of high profile customers so it's pretty battle tested and we've been able to get their free version working in production with no trouble.

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 API Development

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

Create a REST service

I want to create a REST service with PHP 5. I'd appreciate it if people would recommend some guides/tutorials on the subject. I'd like tutorials that cover the whole process, including the creation, securing and deployment of the service. Thanks.
I've been planning on building a full API/REST interface as of yet I've only implemented some features. The key concept that you need to get around is that it is simply a XML/JSON (etc) response to a predefined url.
You can quite easily get set up using .htaccess & mod rewrite to allow domain.com/method/var/id or some similar structure to redirect to domain.com/script.php?method=method&?var=var&?id=id . Once this is done, you can use these in your script, create your response and return it(print/echo) to script.php .
When a user sends a request, they will received the result that you have specified.
Json is very easy to use and implement thanks to http://php.net/manual/en/function.json-encode.php
You want to look into mod rewrite for apache.
As for authentication, it shouldnt differ to any other login/authentication have a look at sessions for php. http://php.net/manual/en/features.sessions.php
Hope this helps.
You could check out the wiki page on it. There is some abstract explaination on the matter.
For more concrete implementation take a look at the Zend package wich I use to build REST services.
I have always used the Zend_Rest libraries when trying to accomplish this task. They are pretty easy to implement and pretty well documented.
Zend_Rest

Generating objects in PHP using REST

I am trying to make a decision whether I should use a REST service or a SOAP service for some web facing functions that I am producing. This decision is based on whether I can easily use the REST service in implementation. I would prefer to use REST, though I don't want to spend days coding the object model in PHP.
The services are being developed in .NET but will be consumed mainly by PHP.
Basically it has come down to one point: Ease of integration. Using SOAP in PHP I can use the NuSOAP library, which will generate the object model.
However with REST I cannot seem to find a way to easily generate that model, if this is possible I would use REST services as they are easier to document and extend, and also have the JSON abilities as well.
Can I generate an object model in PHP from an XML file/schema that I could then serialize with the REST service?
You might not even have to go the class route. Simply ingest the data using simplexml and then traverse it as if it were an object. Or if you have json, json_decode($data, TRUE) would do the same thing (without attributes in brackets).
$ch = curl_init("http://example.com/some/rest/endpoint");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
$obj = simplexml_load_string($data);
print $obj->some->data->you['need'];
That would print here if your XML was something like
<_>
<some>
<data>
<you need="here" />
</data>
</some>
</_>
I had some trouble getting SOAP to work between diffent languages (PHP <> JAVA and PHP <> .NET)
If your going with SOAP, you might want to check out WS-I (Web Services Interoperability)
Based on your described requirements you should stick in the SOAP world. Remember, REST is just a style of architecting a distributed interface. It says nothing about how the functionality of that interface is implemented. There certainly is no need for mapping schemas to objects.
Having said that, if you look at the client tools in the WCF REST Starter kit you will find functionality to paste XML as a CLR type. This will do a best guess at creating a serializable class based on an XML instance document.
Also, from what you are describing ADO.NET Data Services would provide you a quick way of exposing RESTful data services to your PHP site.
....
Here is a question for you? If the .Net services are going to be consumed by a PHP site then why would you describe the .Net services as "web facing". From your description, these services sound more like a private implementation detail of your web site.
If I were you I would:
investigate if NuSOAP tools can be used on just XSD. In the .NET world, you have svcutil (or in the ASMX days, wsdl.exe) to digest .wsdl files to produce proxy classes. But if you have only .xsd files, you can use the xsd.exe tool, or the "aftermarket" XsdObjectGen, which is like a supercharged xsd.exe. Are there similar tools in NuSOAP to do the same? Maybe this is obvious and you've already done it.
if that doesn't pan out, produce a dummy WSDL, and stuff the XSD you have into it. Then, process the .wsdl file with the NuSOAP tools. Grab the generated code, and remove the soap envelope and communications stuff, but retain the object serialization stuff. Not sure if this is possible, the way the PHP (or is it C?) code is generated by the NuSOAP tools. In .NET, it's easy to break the different pieces out.
The whole idea behind rest is that you do not use it with hackish "object models" like with SOAP. The problem is you're trying to use the system wrong :)
If you want object models, use SOAP.
If you want web-friendly APIs, use REST.
For ease of integration, I'd go with a REST API. Since there is such a strong convention, integrating should be relatively straightforward for anybody's who's worked with REST before.
So i think this could be something that i am looking for. but i would like to know if there is some sort of automation system out there for it
found it at http://devzone.zend.com/article/1713#Heading11
Extending Classes
While the above examples were all
doable with PHP 4 and the domxml
extension (only the API was a little
bit different), the ability to extend
DOM classes with your own code is a
new feature of PHP 5. This makes it
possible to write more readable code.
Here's the whole example again,
re-written to use the DomDocument
class:
class Articles extends DomDocument {
function __construct() {
//has to be called!
parent::__construct();
}
function addArticle($title) {
$item = $this->createElement("item");
$titlespace = $this->createElement("title");
$titletext = $this->createTextNode($title);
$titlespace->appendChild($titletext);
$item->appendChild($titlespace);
$this->documentElement->appendChild($item);
} } $dom = new Articles(); $dom->load("articles.xml");
$dom->addArticle("XML in PHP5"); print
$dom->save("newfile.xml");

Categories