How to Write an API for Your Cloud App? API is easy to use, even without documentation and know to be consumer friendly. Let us get started. As we have discussed before, with the intense use of Cloud Computing and the usage of API has been increased. There is RESTful API for WordPress to Enable Public HTTP GET Request for Posts – WordPress became a full fledged Web App. Previously we described about CocoaRestClient – a tool which can be useful to developers using OS X. Most of us, who are using computers for past 2 decades, started with High Level Programming Language like BASIC. We do have certain advantages because for the most of us, there was no GUI. We had to work and write with logical sense. Basically Computer Science is not a rigid discipline that only peoples who traditionally educated in computing, did great works, indeed, the reality is different. The topic is different but basically, many from the health science also want such entry. There are various kinds of peoples, for example a person possibly whom everyone who knows about him loves :
@AbhishekCTRL @digitalps which one was it? Glad it helped!
” Darren Rowse (@problogger) June 10, 2014
Although, these are related more to blogging, there is a reason – Twitter suggested to block a person because of abnormal questions which I never faced in last 5 years or so. I blocked via API. Twitter clearly has various versions of API. But a bad API can expose many higher administrative function to the Public.
How to Write an API for Your Cloud App – Basics
API needs a specific programming language. Designing a good API requires a consideration of the characteristics and idioms of the language you are working with. Some of the most important considerations are :
---
- Whether memory is managed manually, with RAII, or with garbage collection.
- Support for generic programming, object oriented programming, functional programming, etc. in the language.
- What type system the language uses.
Practical fact – writing program is easier, I can write (I do have some) a program in Java for medical usage. But if a person from IT can not understand how, where to start development, it honestly will be unusable. So the best piece of advice we can offer is not to assume there is any language-agnostic universal API design guidelines, and instead get to know the language(s) you’re working with and the appropriate idioms.
An API is a basic library consisting of interfaces, functions, classes, structures, enumerations, etc. for building a software application. It is used by development teams to interact with and extend the software. An API for a given programming language and system may consist of system-defined and user-defined constructs. As the number and complexity of these constructs increases, it becomes very tedious for developers to remember all of the functions and the parameters defined. Hence, the API writers play a key role in building software applications.
An API writer is a technical writer who writes documents that describe an application programming interface (API) following The Chicago Manual of Style for grammar and punctuation. The primary audience includes programmers, developers, system architects, and system designers.
How to Write an API for Your Cloud App – Getting Started
We are talking about RESTful Request for Cloud App. Every REST request consists of essentially the same basic parts:
- The URL “ This is the URL we will be making a request against
- The Verb “ GET, POST, PUT, or DELETE there are some others out there, but these are the 4 most common ones.
- The Params “ The parameters we will be supplying to the API, often referred to as the request body.
- Credentials “ Username and password¦ we™ll cover HTTP Digest auth credentials.
And, of course, we™ll have a few pieces for our response as well:
- The Response Body “ The actual response body the API gave us.
- The Response Status Code “ The HTTP status code the API responded with.
- Other Response Info “ We will also have some other interesting info in the response.
Nothing really unexpected here – a request and a response. There are several ways of writing code to work with cloud services. To put the Simple Cloud API in context, we’ll look at APIs at four levels:
- The wire
- Language-specific toolkits
- Service-specific toolkits
- Service-neutral toolkits
At The Wire level, you are concerned with the actual bytes that go across the connection from the application to the cloud. For a SOAP service, the application has to build the <SOAP:Envelope>
with the appropriate contents and headers. For a REST service, the application has to create the correct HTTP headers and build a URL that contains the appropriate parameters. A language-specific toolkit provides convenience classes to create the SOAP and REST data structures. Usually cURL is used to rescue.
How to Write an API for Your Cloud App – Copying Ian
This part is fully copied from gen-x-design.com
written by Ian in PHP, this is the best reference on API in practical life. The website sometimes is online, sometimes goes off, people usually refer to Way Back Machine.
If you have ever worked with Curl in PHP, you™re probably aware that making GET and POST requests are pretty straight-forward, but the PUT and DELETE requests are a little less obvious. Luckily, they™re pretty easy once you know how to do them, the problem is that they™re very poorly documented. We™ll go over them soon, but let™s get started with a little code. We™re going to be building a class that we can use to make requests and deal with their responses, so why don™t we build up a bit of a base class, and then start filling things in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | class RestRequest { protected $url; // $url “ The URL we will be requesting protected $verb; // $verb “ The type of request protected $requestBody; // $requestBody “ The request body we will send protected $requestLength; // $requestLength “ An internally used variable for PUT requests protected $username; // $username “ The username to use for this request protected $password; // $password “ I do not know protected $acceptType; // $acceptType “ What kind of content we can accept as a response protected $responseBody; // $responseBody “ The body of our response protected $responseInfo; // $responseInfo “ All the other goodness from our response public function __construct ($url = null, $verb = 'GET', $requestBody = null) { $this->url= $url; $this->verb= $verb; $this->requestBody= $requestBody; $this->requestLength= 0; $this->username= null; $this->password= null; $this->acceptType= 'application/json'; $this->responseBody= null; $this->responseInfo= null; if ($this->requestBody !== null) { $this->buildPostBody(); } } public function flush () { $this->requestBody= null; $this->requestLength= 0; $this->verb= 'GET'; $this->responseBody= null; $this->responseInfo= null; } public function execute () { } public function buildPostBody ($data = null) { } protected function executeGet ($ch) { } protected function executePost ($ch) { } protected function executePut ($ch) { } protected function executeDelete ($ch) { } protected function doExecute (&$curlHandle) { } protected function setCurlOpts (&$curlHandle) { } protected function setAuth (&$curlHandle) { } } |
We™ve also got a flush function. This allows us to use the same object to make multiple requests by only clearing out certain member variables. This function will take an array and prepare it for being posted (or put as well):
1 2 3 4 5 6 7 8 9 10 11 12 | public function buildPostBody ($data = null) { $data = ($data !== null) ? $data : $this->requestBody; if (!is_array($data)) { throw new InvalidArgumentException('Invalid data input for postBody. Array expected'); } $data = http_build_query($data, '', '&'); $this->requestBody = $data; } |
This function will take care of all the curl options common to all our requests:
1 2 3 4 5 6 7 | protected function setCurlOpts (&$curlHandle) { curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10); // arbitrary, 0 is no limit curl_setopt($curlHandle, CURLOPT_URL, $this->url); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array ('Accept: ' . $this->acceptType)); } |
If we™ve got a username and password set on the class, we™ll set up the auth options on the curl request with this function:
1 2 3 4 5 6 7 8 | protected function setAuth (&$curlHandle) { if ($this->username !== null && $this->password !== null) { curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_setopt($curlHandle, CURLOPT_USERPWD, $this->username . ':' . $this->password); } } |
We™re about ready to cover how to make the individual verb requests, but we need to do just a little bit more work filling in the common functionality. We™ll go ahead and create our doExecute and execute functions now:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public function execute () { $ch = curl_init(); $this->setAuth($ch); try { switch (strtoupper($this->verb)) { case 'GET': $this->executeGet($ch); break; case 'POST': $this->executePost($ch); break; case 'PUT': $this->executePut($ch); break; case 'DELETE': $this->executeDelete($ch); break; default: throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.'); } } catch (InvalidArgumentException $e) { curl_close($ch); throw $e; } catch (Exception $e) { curl_close($ch); throw $e; } } protected function doExecute (&$curlHandle) { $this->setCurlOpts($curlHandle); $this->responseBody = curl_exec($curlHandle); $this->responseInfo= curl_getinfo($curlHandle); curl_close($curlHandle); } |
This is a REST request :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public function execute () { $ch = curl_init(); $this->setAuth($ch); try { switch (strtoupper($this->verb)) { case 'GET': $this->executeGet($ch); break; case 'POST': $this->executePost($ch); break; case 'PUT': $this->executePut($ch); break; case 'DELETE': $this->executeDelete($ch); break; default: throw new InvalidArgumentException('Current verb (' . $this->verb . ') is an invalid REST verb.'); } } catch (InvalidArgumentException $e) { curl_close($ch); throw $e; } catch (Exception $e) { curl_close($ch); throw $e; } } protected function doExecute (&$curlHandle) { $this->setCurlOpts($curlHandle); $this->responseBody = curl_exec($curlHandle); $this->responseInfo= curl_getinfo($curlHandle); curl_close($curlHandle); } |
GET will be simple :
1 2 3 4 | protected function executeGet ($ch) { $this->doExecute($ch); } |
Up to this what Ian wrote and you can check :
1 | https://web.archive.org/web/20130323001500/http://www.gen-x-design.com/archives/making-restful-requests-in-php/ |
Many web site badly copies and claims the snippet to be of them. If you find such, please ask them to give credit to Ian for the coding part and link to that way back machine’s page. It is bad to copy someone others stuff and not give a credit.
How to Write an API for Your Cloud App – Other Stuffs
.htaccess file provides directory level configuration on Apache web server to handle requests to rthe esources in the directory the .htaccess file itself lives in. Let us create a .htacccess file :
1 2 3 4 5 6 | <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule api/v1/(.*)$ api/v2/YourAPI.php?request=$1 [QSA,NC,L] </IfModule> |
We created as we do not wish to have to create new PHP files for every endpoint. Phalcon is a web framework implemented as a C extension offering high performance and lower resource consumption. If you use Phalcon, you can follow this guide (quite nicely written) :
1 | http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html |
As in real life we rarely need to build an App from scratch, but possibly most starts from a framework, we actually do not need to proceed in the described way. So, many new things can complicate your App, like if you are developing an iOS App which will access Rackspace OpenStack Swift based storage, you need to read their docs too.
Tagged With how to write API for cloud applications