I have recently been asked to create an API that can process data using PHP. I am not that accustomed to PHP so I am not quite sure how to proceed.
Basically what I would like to achieve is create an API that processes a form post that the user can call like this:
<form METHOD="POST" ACTION="https://MyURL/index.php" id=aForm name=aForm> <input type="hidden" id="Lite_Merchant_ApplicationID" name="Lite_Merchant_ApplicationID" value="Your Application Id"> (various other fields to be processed) </form>
I might be wrong in calling this an API, because it's supposed to handle a form post. But I need to compile documentation for users to be able to integrate with our system and post the form to our URL which will then process the info in the form.
Are there any good tutorials that I can have a look at? I am not sure if the ones I am looking at are applicable as they mention nothing about using a form to call the API? e.g. https://docs.phalconphp.com/en/latest/reference/tutorial-rest.html and http://coreymaynard.com/blog/creating-a-restful-api-with-php/
Or do I just process the form as normal in PHP and accesss the values using:
$_POST["name"];
If that is the case will users be able to call the API using the language of their choice?
An additional question I have would be if there is anything I would need to look at or consider due to the fact that it will be "https"?
Thanks in advance and my apologies if this is not very specific, any advise/pointers will be appreciated.
Additional info: The system needs to be able to perform redirects and login credentials will be sent within the hidden form inputs
5 Answers
Answers 1
Your question is a little wide ranging, and you may be using words in a way that isn't consistent my understanding.
An API typically is more than a single method, whereas handling a form POST event is just - well, a form handler. The difference is more than semantic - for an API, you probably need to consider versioning (how do you upgrade your API without breaking client applications), abstraction (how can you make your API easy to use), documentation, and security (how can you ensure that only authorised users/applications consume your API?). An API often has more than one user, and often needs to support the scalability requirements of the client applications.
REST is a great way to design an API - it's easy to understand for clients, and lots of smart people have solved problems like authentication/authorisation, versioning and abstraction.
It's important to note that REST uses existing HTTP concepts, so a RESTful API would expose POST requests to create new entities. That POST request can be called from a web page with a <form>
element, or from a REST client. If you write a RESTful API, clients can be written in any language that supports HTTP.
There are a bunch of frameworks which make building RESTful web APIs easier in PHP. I haven't used any, so can't make a recommendation.
If, however, all you have to do is handle a POST request, from a web page that won't change - well, I'd not build a RESTful API, I'd just write a PHP "POST" handler. In this case, the client can be anything that understands your POST parameters (in practice, pretty much any application that can make an HTTP request).
However, the difference between "POST Handler" and "API" in my view is that when you create an API, you make certain promises that your clients depend on. "I won't change the field names without telling you". "I won't change the location without telling you". "You can depend on what my documentation says". When you create a POST handler, you only promise the maker of the HTML form that it works, and that you will tell that team of any changes.
The only challenge with HTTPS is that you must make sure that the calling application can handle it, and that the keys work.
Answers 2
Just process the form as normal in PHP and accesss the values using:
$_POST["name"];
The API user just has to send a POST request, by html form, AJAX, or whatever. You should add a field for the response format html, xml, json, then use that to format the response.
Answers 3
Check below links (restful services)... Its very simple and meets your requirement.
http://rest.elkstein.org/2008/02/what-is-rest.html
http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html
Answers 4
Going along with Neville K's answer here is an example of how my company handles RESTful api calls.
First we have a php file that handles the calls with a switch statement. Routing the different actions to said functions and classes.
/* Class file that is called on this page */ include_once "$_SERVER[DOCUMENT_ROOT]/classes/class.myclass.php"; /** * This function makes it simpler to stop it from working for debugging purposes. * All we have to do is comment out the one line of code apiCall($_REQUEST); * You could have this outside of the function and it would work just as well. * @param type $REQUEST */ function apiCall($REQUEST) { $con = new MyClass(); switch ($REQUEST['action']) { case 'getList': /* Setting the content type to json means that the developer can * expect a response in the form of parseable json. */ header('Content-Type: application/json'); echo json_encode($con->getList($REQUEST)); case 'setValue': header('Content-Type: application/json'); echo json_encode($con->setValue($REQUEST)); case 'login': if ($con->login($REQUEST)) { header('Location: /index.php'); } else { header('Content-Type: /login.php?status=Failed+Login'); } default: header('Content-Type: application/json'); /* If an invalid action was sent in, then this error message will be sent * back to the user */ echo json_encode(['status' => 'Invalid API Call']); } } /* Using $_REQUEST allows developers to access the api via GET or POST */ apiCall($_REQUEST);
Then we handle all the logic in the different classes we called.
class MyClass { public function getList($REQUEST) { $id = $REQUEST['id']; /* code */ return ['status' => 'ok', 'results' => $array]; } public function setList($REQUEST) { /* code */ return ['status' => 'ok']; } public function login($REQUEST) { /* code */ $_SESSION['user_id'] = $user_id; return $login_successful; } }
Using JSON
is good for applications that send information via AJAX
calls. Using the header('Location:')
are good for form submissions without ajax.
You can then use JavaScript ajax calls or for submissions based on how you handle the submission of data.
Example of using jQuery.getJSON
$.getJSON('/switch.php', $.param({id: id, action: 'getList'}), function (json) { if (json) { /*code*/ } });
Then you would pass a hidden input with action in it to the switch page for regular form submissions.
<form action="/switch.php" method="post"> <!--hidden input named action to direct which switch to use--> <input name="action" value="login" type="hidden"/> <input name="username"/> <input name="password" type="password"/> <input type="submit"/> </form>
These examples are for html/JavaScript web applications. If you are using JAVA, Python, .NET, or some other language, it would be as simple as using the REST API and parsing out the JSON to figure out how to handle your application logic.
You can even run a php to php api call using file_get_contents
or curl
.
$data = [ 'action' => 'setValue', 'information' => 'More' ]; $json = json_decode(file_get_contents('/switch.php?' . http_build_query($data)),true); if(!empty($json)){ /*code*/ }
You could create a seperate page for each call and not have to worry about passing in an action
to every request. But then your filetree starts to look like this.
/api/loginSubmit.php /api/login.php /api/getListFromId.php /api/getList.php /api/setValues.php /api/getValues.php
It gets really tedious to traverse all these files to figure out where the problem is.
Answers 5
I created API Framework, its very light weight, simple, fast.
Github
OR
0 comments:
Post a Comment