Restler API — Beginner’s Guide

Restler API — Beginner’s GuideSuccessiveTechBlockedUnblockFollowFollowingFeb 1Restler 3.

0As the Official site states “Just deal with your business logic in php, Restler will take care of the REST!This was the exact excerpt from the official documentation of Restler.

And this can’t be made any simpler than that.

But if you are still figuring out I have sorted that out for you.

It states that you only need to write the logic for your application and Restler is going to spread its charm all over it and you are left with a simple, versatile and a faster more lighter API server.

IntroductionRestler is just a server framework that is lightweight and is written in PHP.

Restler’s main advantage is its simplicity.

You just need to create a class and expose some functions from it.

And that’s all.

You are all set up for work.

Comparison with other PHP micro frameworksPrerequisiteIf you have any idea about how to write object oriented PHP, then you are all set to use Restler.

Advantages of using RestlerRestler is light and easy to use.

All public methods are automatically mapped to a URL.

It is free and open sourced.

More customizable:-Add your own authentication class.

Supports different formats like json, xml, yaml etc.

Simply declare function as protected and add an authentication class.

Target usersDevelopers who need a RESTful API server.

Some of the Features of using RestlerLightweight and flexible.

Customizable.

Supports HTTP request methods — POST, GET, PUT and DELETE.

URL to function mapping.

Comes with JSON, XML, YAML, AMF, and PLIST (both XML and Binary) formats.

Clients can use X-HTTP-Method-Override header.

Pluggable authentication schemes.

Restler execution flowFollowing are the main steps that Restler goes through in its entire lifetime:-When any HTTP request is made, the method is determined(GET, POST, PUT and DELETE).

Matching API URL is searched and if it is not present then an error is thrown as a response, otherwise it proceeds to the next step.

If the URL is successfully found out then it is made sure that it is a protected API.

If it is not a protected API then the API Method is executed directly and we are provided with a response.

But if it is a protected API, then it is again checked for authentication and if it is not authenticated then an error is thrown as a response to that call.

If it is authenticated successfully, then the API method is executed successfully and the result is provided as a response.

The flow diagram below is taken from the official Restler site and it is pretty clear how Restler works.

You can verify the above steps with this flow diagram.

It is explains the exact thing.

Simple example showing the use of Restler:-Example 1:-class Welcome { function hello($user=’User’) { return “Welcome $user!”; } function hi($user) { return “Hi $user!”; }}Now, the following links can be called:-GET welcome/helloOUTPUT:- Welcome User!GET welcome/hi?user=PrawalOUTPUT:- Hello Prawal!Example 2:-function multiply($n1, $n2) { return array( ‘result’ => ($n1 * $n2) ); }OUTPUT:-GET math/multiply/6/2OUTPUT:- {“result”:12}Do not forget to visit the official page for more info regarding Restler.

https://www.

luracast.

com/products/restlerRestler basic setupIn this section we are going to see Restler in action, how to install and setup it.

With basic routing, some examples, error responses and the API explorer that is provided to us with Restler.

InstallationMake sure at least PHP 5.

3.

4 is available on your server before installing Restler.

There are two ways using which you can install Restler on your system.

Install using composerphp composer.

phar create-project luracast/restler {projectName}2.

Download from githubgit clone https://github.

com/Luracast/Restler.

gitThis command is going to create a directory by the name Restler on the source path where you ran this command from.

Quick start guideOnce you have got Restler set up using the above steps, you can quickly create your application by using the following steps.

Here we are going to create CRUD APIs for product inventory based website where we will be able to perform all the operations like reading, inserting, editing and deleting for product resource.

Project setupAfter installing Restler through any of the above methods, when you first run the project you will get some documentation pages with examples.

To clear that up, follow these steps:Step 1 : Remove all the files from public folder.

Step 2 : Add a file index.

php as given below to bootstrap Restler .

Step 3 : Add .

htaccess file for pretty URLsStep 4 : Create a folder app in project root it will hold all our API classes.

Step 5 : Add psr entry to the composer.

json file to make our classes available.

Open the gatewayIn our project, index.

php file is the gateway to access all the available resources.

It’s the index.

php file where all of the requests are hit and those get redirected to appropriate API class as per the routing.

To make our API class callable we need to create a gateway in our index.

php file as follows.

<?phprequire_once ‘.

/vendor/restler.

php’;use LuracastRestlerRestler;$r = new Restler();$r->addAPIClass(‘Product’); // repeat for more$r->handle(); //serve the responseIn the above code we create an object for Restler and then adding/registering our Product API class to Restler object using addAPIClass() method.

Like this we we can add more API classes we need.

Enable URL rewritingMake sure to route all the requests to index.

php by enabling URL rewriting.

For example:-If you are on the apache server, then you can use .

htaccess file.

In our example we are using an Apache server so we will create a .

htaccess file like the one below.

DirectoryIndex index.

php<IfModule mod_rewrite.

c> RewriteEngine On RewriteRule ^$ index.

php [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.

*)$ index.

php [QSA,L]</IfModule><IfModule mod_php5.

c> php_flag display_errors On</IfModule>Now let’s move forward for creating our first application.

At first, we will be creating a table in the database where all our data will be saved for products.

Creating table structureThe sql command for the table products is as given below:-CREATE TABLE `products` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `description` text NOT NULL, `sku` varchar(50) NOT NULL, `price` decimal(9,2) NOT NULL, `vendor_id` int(11) NOT NULL, `category_id` int(11) NOT NULL, `created_at` datetime NOT NULL, `modified_at` datetime NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;Now, let’s create our API class with all the CRUD operations for this table/resource.

But before doing that we need to first know how routing works in Restler, because we need to call those functions that we will create in our API class.

Restler provides us with a very easy way to do so.

RoutingTwo ways of routing:-Automatic routing.

Manual routing.

Automatic routing:-Restler uses get, put, post, delete, and patch as prefix to map PHP methods to respective HTTP methods.

When they are used method names without any suffix they map at the class level similar to index{HTTP_METHOD} class_nameGET is the default HTTP method so all public functions without any of these prefixes will be mapped to GET request.

This means functions getNames and names will both be mapped toGET class_name/namesSimilarly method postSomething will be mapped toPOST class_name/somethingManual routing:-These can be created manually using phpdoc comment as shown below.

We can specify as many routes as we want for a single method.

Comment structure is as shown below@url {HTTP_METHOD} path_segment_including_url_parametersFor example:-@url POST custom/path/{var1}/{var2}Now let’s start with the code for our product API.

We are going to create a Product class first and then we will add all our needed functions to it.

In this Product.

php class we will create the following 5 functions to each of the route.

HTTP methodRouteMethodDescriptionGET/productindex()To read/get all productsGET/product/{id}get($id)To get a single productPOST/productpost()create a new productPUT/product/{id}put($id)update existing productDELETE/product/{id}delete($id)delete a productIn our product API example we are going to use PDO to connect to database .

Let’s create PDO object in our product.

php classclass Product { protected $db;public function __construct() { $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => ‘SET NAMES utf8’, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); $this->db = new PDO( ‘mysql:host=localhost;dbname=Restler_db’, ‘root’, secret, $options ); $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); }}1.

Read/Get productsLet’s write our first URL endpoint with the function index(), this function will be mapped with the GET /product URL.

In this function we simply fetch all the records from the product table and return results of associative array.

Restler will automatically create it’s json format for us.

public function index() { $sql = $this->db->prepare(‘SELECT * FROM products’); $sql->execute();$data = $sql->fetchAll(); if (!$data) { throw new RestException(404); } return [‘status’ => true, ‘data’ => $data]; }The above function is named index, which is going to be treated as a GET URL whenever we are going to call our API class product.

You can also see a line asthrow new RestException(404);Restler provides a RestException class to all the API methods to provide error information to the user.

The basic use is like throw new RestException($httpStatusCode) to send the error response to the client, where $httpStatusCode are the HTTP status codes.

This can also take a second parameter as an error message.

Output :{ “status”: true, “data”: [ { “id”: “1”, “name”: “voluptatem”, “description”: “Et nisi ratione eum odit.

”, “sku”: “0b3758e4–1424–3349-b90d-344d415fe198”, “price”: “9.

00”, “vendor_id”: “1”, “category_id”: “1”, “created_at”: “2018–08–10 16:00:03”, “modified_at”: “2018–08–10 16:00:03” }, { “id”: “2”, “name”: “quae”, “description”: “At in non placeat.

”, “sku”: “10b134ee-eddb-3d06-b9ac-604741f14010”, “price”: “60.

00”, “vendor_id”: “5”, “category_id”: “3”, “created_at”: “2018–08–10 16:00:03”, “modified_at”: “2018–08–10 16:00:03” },….

… ]}2.

Read/Get a single product dataTo read the details of a specific product we need to have another source.

We will be creating another API just to read all the details from the database regarding any product that we will be having.

This is an example of the automatic routing where if id is being provided to a GET request then this below method is going to be executed.

public function get($id) { $sql = $this->db->prepare(‘SELECT * FROM products WHERE id= :id’); $sql->execute(array(‘:id’ => $id));$data = $sql->fetch(); if (!$data) { throw new RestException(404); } return [‘status’ => true, ‘data’ => $data]; }Output :We can see that the output is the record for the specific product.

{ “status”: true, “data”: { “id”: “1”, “name”: “voluptatem”, “description”: “Et nisi ratione eum odit.

”, “sku”: “0b3758e4–1424–3349-b90d-344d415fe198”, “price”: “9.

00”, “vendor_id”: “1”, “category_id”: “1”, “created_at”: “2018–08–10 16:00:03”, “modified_at”: “2018–08–10 16:00:03” }}3.

Insert/Add new productNow suppose there are more products that we need to add to our product catalog in the database.

To achieve this we are going to create an API to insert new products along with all their necessary details.

Similarly, this is a POST method to insert new data in the database for various products.

This is also an example of the automatic routing.

public function post($request_data = NULL) {$sql = $this->db->prepare(“INSERT INTO products (name, description,sku,price,vendor_id,category_id,created_at,modified_at) VALUES (:name,:description,:sku,:price,:vendor_id,:category_id,:created_at,:modified_at)”); $data = array( ‘:name’ => $request_data[‘name’], ‘:description’ => $request_data[‘description’], ‘:sku’ => $request_data[‘sku’], ‘:price’ => $request_data[‘price’], ‘:vendor_id’ => $request_data[‘vendor_id’], ‘:category_id’ => $request_data[‘category_id’], ‘:created_at’ => date(‘Y-m-d H:i:s’), ‘:modified_at’ => date(‘Y-m-d H:i:s’), );try { $result = $sql->execute($data); } catch (Exception $ex) { throw new RestException(400, $ex->getMessage()); }if (!$result) { throw new RestException(400); } return [‘status’ => true]; }Output:This was the output stating that the data inserted successfully.

To check this you can go to the database and look for the products table and find your newly inserted data present there.

{ “status”: true}4.

Update/modify a productWhat if we have added a product with some incorrect details in our database.

Or there is a case of price change, description change or any other details that need to be modified or edited.

So now we are going to create a method which is going to update any product whose id will be given.

This is the PUT method to edit and update the products table.

public function put($id, $request_data = NULL) { $sql = $this->db->prepare(“UPDATE products SET name=:name, description =:description,sku= :sku,price=:price,vendor_id=:vendor_id,category_id=:category_id,modified_at = :modified_at WHERE id = :id”); try { $result = $sql->execute(array( ‘:name’ => $request_data[‘name’], ‘:description’ => $request_data[‘description’], ‘:sku’ => $request_data[‘sku’], ‘:price’ => $request_data[‘price’], ‘:vendor_id’ => $request_data[‘vendor_id’], ‘:category_id’ => $request_data[‘category_id’], ‘:modified_at’ => date(‘Y-m-d H:i:s’), ‘:id’ => $id ) ); } catch (Exception $ex) { throw new RestException(400, $ex->getMessage()); }if (!$result) { throw new RestException(400); } return [‘status’ => true]; }Output:This was the output stating that data was updated successfully.

To check that you can go to the database, look for the products table and find your data there.

{ “status”: true}5.

Delete a product recordThere can be a case where we just don’t want any specific product on our catalog or we just want to remove it.

So we need another API to delete the products that are no more required.

This is a DELETE method to delete a specific product from the database based on the id provided.

public function delete($id) { $sql = $this->db->prepare(‘DELETE FROM products WHERE id= :id’); $result = $sql->execute(array(‘:id’ => $id));if (!$result) { throw new RestException(400); } return [‘status’ => true]; }Output:This was the output stating that the record was deleted successfully.

To check that you can go to the database, look for the products table and search for the id of the record that you just deleted.

It will not be there anymore.

{ “status”: true}An Example showing the use of manual routing:-Now, let’s create a custom URL using phpdoc comment as shown below.

In the below example we are going to create a manual route with name category to show all the products from a particular category.

Url : api/product/category/{id}Here the function name is productByCategory() but we have defined a URL category/{catId} which is going to be a GET request.

This is an another effective way to create URLs and provide routing for the various API methods.

/** *  * @param int $catId * @url GET category/{catId} */ public function productByCategory($catId){ $sql = $this->db->prepare(‘SELECT * FROM products WHERE category_id= :cat_id’); $sql->execute(array(‘:cat_id’ => $catId));$data = $sql->fetchAll(); if (!$data) { throw new RestException(404); } return [‘status’ => true, ‘data’ => $data]; }Output:{ “status”: true, “data”: [ { “id”: “1”, “name”: “voluptatem”, “description”: “Et nisi ratione eum odit.

Dolor blanditiis fugiat id voluptatibus qui ipsam qui.

Aperiam rerum sunt id officia.

”, “sku”: “0b3758e4–1424–3349-b90d-344d415fe198”, “price”: “9.

00”, “vendor_id”: “1”, “category_id”: “1”, “created_at”: “2018–08–10 16:00:03”, “modified_at”: “2018–08–10 16:00:03” }, { “id”: “11”, “name”: “nemo”, “description”: “Quia delectus atque iste corrupti nihil.

Quibusdam tempora vitae ipsam dolorem et.

Alias odio et et esse velit voluptas.

Aut qui deserunt aut sit totam voluptatem.

”, “sku”: “5c19f5e0-cc22–33e9-a6eb-85af7655b01a”, “price”: “99.

00”, “vendor_id”: “17”, “category_id”: “1”, “created_at”: “2018–08–10 16:00:03”, “modified_at”: “2018–08–10 16:00:03” },.

 ]}Implementing API explorer with swaggerUsing API explorer we can document our APIs so that the users can really explore them.

Restler has a built in SwaggerUI modified as Restler API Explorer.

To add API Explorer we need to follow the step defined in this link.

https://github.

com/Luracast/Restler-API-Explorer.

But if you don’t have a lot of time, then don’t worry!.I have written these below for you.

There are basically only two steps that you need to follow:-Copy the dist folder to Restler based API root, and rename it to explorer from the above git repo.

Add this line to the index.

php of your application.

$r->addAPIClass(‘LuracastRestlerResources’);Open /explorer link in your browser to see the APIs appear magically.

Below is the snapshot of the API class product that we created with all the CRUD operations.

And if you see you can find all the methods that we have written there.

Listing of all the APIs present in the Product class:-You can play around with the explorer as much as you want.

Restler in More DepthIn this section we are going to get into more detailed features that Restler provides us like rate limiting, access control, Oauth and various other features such as multiple response formats & versioning.

We will be using the same example in the last section regarding Products application in this tutorial also.

So let’s start with this guide.

Multi Response FormatJsonFormat is the default response format used by Restler.

Restler::setSupportedFormats() function is used to specify which formats can be used by the API class.

When client does not specify any format, first format set in setSupportedFormats() function is used as the default.

Client can specify the format either using extension like .

json or specify the MIME type in HTTP Accept Header.

When we make the request from the browser we will get xml when we skip the extension because XML is one of the requested formats specified in the HTTP Accept Header.

We can add various formats for responses like shown below for our Products application where we are specifying the json and xml both the formats.

$r = new Restler();$r->addAPIClass(‘Product’);$r->setSupportedFormats(‘JsonFormat’, ‘XmlFormat’);$r->handle();Json format response: To get the response in the json format we either need to add .

json in the URL as an extension (like api/product.

json/1) or add accept in the request header as application/json.

In the below screenshot you can see the response of our product API get request in the json format.

XML format Response : Same like json, to get the response in the xml format we either need to add .

xml in the URL as an extension (like api/product.

xml/1) or add accept in request header as application/xml.

In the below screenshot you can see the response of our product API get request in the xml format.

Rate limitingRate limiting is a feature of adding limit to a particular resource access suppose if we want to restrict our API consumer to only 1000 request calls per day or per month.

We need to add the below line to the index.

php file to enable rate limiting to our product application.

$r->addFilterClass(‘RateLimit’);There are two ways to implement rate limiting in APIs:-Global limitBelow is the code from the index.

php for our Products application.

As you can see we have used Restler’s built in class RateLimit and set up the limit for 2 hits per minute for all the classes defined here which is only the Product class.

It means that all the methods in the Product class will be limited to 2 hits per minute.

Then the user needs to wait for a minute before he/she is again able to make calls to these methods successfully.

use LuracastRestlerFilterRateLimit;// Limit applied to all the classesRateLimit::setLimit(‘minute’, 2);$r = new Restler();$r->addAPIClass(‘Product’);$r->addFilterClass(‘RateLimit’);$r->handle();2.

Individual limit:We can also use phpdoc comments to implement rate limiting for individual methods.

/** * @class RateLimit {@unit minute} {@usagePerUnit 5} */ function get($id) { …This method is going to override the global limit and use this limit for 5 hits per minute as defined in the above phpdoc comment.

Access controlWe need to protect some of our APIs, as we don’t want all of them to be exposed to the public.

There are many ways to achieve this:-Make your functions protected.

Add @access protected doctype comment to the class or methods to make them protected.

We need to use a class that implements iAuthenticate interface to provide access to those protected methods.

So let’s create a class with the name AccessControl.

php and implement its __isAllowed() function of iAuthenticate interface and add our logic for authenticated requests.

<?phpuse LuracastRestleriAuthenticate;use LuracastRestlerResources;use LuracastRestlerDefaults;class AccessControl implements iAuthenticate{ public static $requires = ‘user’; public static $role = ‘user’;public function __isAllowed() { $roles = array(‘user_secret’ => ‘user’, ‘admin_secret’ => ‘admin’); $userClass = Defaults::$userIdentifierClass; if (isset($_GET[‘api_token’])) { if (!array_key_exists($_GET[‘api_token’], $roles)) { $userClass::setCacheIdentifier($_GET[‘api_token’]); return false; } } else { return false; } static::$role = $roles[$_GET[‘api_token’]]; $userClass::setCacheIdentifier(static::$role); Resources::$accessControlFunction = ‘AccessControl::verifyAccess’; // print_r(static::$requires); //die; return static::$requires == static::$role || static::$role == ‘admin’; }public function __getWWWAuthenticateString() { return ‘Query name=”api_token”’; }}Here we have just provided the hardcoded secret keys that are going to help in providing access to the users of the APIs (You can use database based storage for user and their roles).

We need to register our AccessControl class to the index.

php$r->addAuthenticationClass(‘AccessControl’);Now we just need to add phpdoc comments like those below with the name of the role and this API will only be accessible to an admin user giving “admin_secret” in the “api_token”.

/** * @access protected * @class AccessControl {@requires admin} */ public function get($id) { …In the below snapshot, we can see the URL that we used to make request, there is a querystring — api_token with the value “admin_secret”.

You can play with this and change this to “user_secret” to see if the API is now accessible or not.

Note: All the public methods that does not begin with _ will be exposed as an API because an authentication class is also an API class.

As an added bonus we also restrict API documentation(API Explorer) based on the same.

VersioningRestler supports both URL based versioning and vendor specific media type versioning.

You can learn more about vendor based versioning in the official Restler site.

We are going to see the URL based versioning in this guide.

Only integers are supported for versioning.

When not specified explicitly the version is assumed to be one.

We need to modify our index.

php file asDefaults::$useUrlBasedVersioning = true;$r = new Restler();$r->setAPIVersion(2);//…The above changes in our index.

php file are going to set the API version to 2.

And we have also specified that we are going to use URL base versioning by setting $useUrlBasedVersioning = true;First make two folders namely “v1” and “v2”.

Add our Products class to both these folders with some changes to differentiate them both from each other.

Now go to the browser and type the URL and add a v1 before the API name as shown in the one below.

http://restler.

local/api/v1/product/We will see that the API class from the folder v1 should be called and if we change it to v2.

The content from the API class v2 folder should be visible.

So this way we can specify URL based versioning to our Product application.

Add authentication with OAuth 2.

0Authentication is an important part for securing our API from any unauthorised access, So let’s add authentication using OAuth 2.

0 .

We will be using bshaffer’s OAuth library for this (https://github.

com/bshaffer/oauth2-server-php).

There are different grant types available for authentication (Implicit, Authorization Code, Password Credentials, Client Credentials)But we are going to implement “Password Credentials” grant type.

So let’s start by setting up database schema as belowCREATE TABLE `oauth_clients` ( client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000), grant_types VARCHAR(80), scope VARCHAR(4000), user_id VARCHAR(80), PRIMARY KEY (client_id));CREATE TABLE `oauth_access_tokens` ( access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), PRIMARY KEY (access_token));CREATE TABLE `oauth_authorization_codes` ( authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), id_token VARCHAR(1000), PRIMARY KEY (authorization_code));CREATE TABLE `oauth_refresh_tokens` ( refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), PRIMARY KEY (refresh_token));CREATE TABLE `oauth_users` ( username VARCHAR(80), password VARCHAR(80), first_name VARCHAR(80), last_name VARCHAR(80), email VARCHAR(80), email_verified BOOLEAN, scope VARCHAR(4000), PRIMARY KEY (username));CREATE TABLE `oauth_scopes` ( scope VARCHAR(80) NOT NULL, is_default BOOLEAN, PRIMARY KEY (scope));CREATE TABLE `oauth_jwt` ( client_id VARCHAR(80) NOT NULL, subject VARCHAR(80), public_key VARCHAR(2000) NOT NULL);To implement OAuth server we need to add bshaffer’s OAuth server package to aur application, this package is already added in Restler’s composer.

json file.

If it’s not then you need to run the following command to add it to your project.

$ composer require “bshaffer/oauth2-server-php”.

After adding this package we need to configure it with our database (auth storage) and need to create our endpoint’s that user can hit to get access token.

So let’s create a class with the name Oauth.

php and add the following code to it.

In the below code we initialize server object of bshaffer’s library in constructor of our OAuth class with “Pdo” storage and “User Credentials” grant type.

After configuration we add a function postToken() to provide an endpoint through which user can get access token.

Again in this function we only need to call server object handleTokenRequest() function inside postToken() and it will handle the rest of the things for us.

<?phpnamespace Auth;use LuracastRestleriAuthenticate;use OAuth2GrantTypeUserCredentials;use OAuth2StoragePdo;use OAuth2Server as OAuth2Server;use OAuth2GrantTypeAuthorizationCode;use OAuth2Request;use OAuth2Response;/** * Class OAuth * * @package Auth * */class OAuth implements iAuthenticate{ /** * @var OAuth2Server */ public static $server; /** * @var Pdo */ public static $storage; /** * @var Request */ public static $request;public function __construct() {  static::$storage = new Pdo( array(“dsn” => “mysql:host=localhost;dbname=Restler_db”, “username” => ‘root’, “password” => ‘password’) ); // create array of supported grant types $grantTypes = array( ‘authorization_code’ => new AuthorizationCode(static::$storage), ‘user_credentials’ => new UserCredentials(static::$storage), ); static::$request = Request::createFromGlobals(); static::$server = new OAuth2Server( static::$storage, array(‘enforce_state’ => true, ‘allow_implicit’ => true), $grantTypes ); }/** * * @format JsonFormat,UploadFormat */ public function postToken() { static::$server->handleTokenRequest(static::$request)->send(); exit; }/** * Access verification method.

 * * API access will be denied when this method returns false * * @return boolean true when API access is allowed; false otherwise */ public function __isAllowed() { return self::$server->verifyResourceRequest(static::$request); }public function __getWWWAuthenticateString() { return ‘Bearer realm=”example”’; }}Request to get access tokenTo get the access token for authentication we need to do a post request with data grant_type as password, client_id, username and password.

After a successful request it will return us an access token along with a refresh token.

Request to access a protected resource with access tokenTo access any protected resource we need to pass the access token in the header or query string.

In the below example we use Authorization header to pass access token we received from access token request and if valid it allows us to access the resource.

And as you can see we are successfully able to call the API.

This was how authentication with Oauth is implemented in Restler.

This marks the end of this tutorial.

.. More details

Leave a Reply