You are viewing our old blog site. For latest posts, please visit us at the new space. Follow our publication there to stay updated with tech articles, tutorials, events & more.

Rest API

0.00 avg. rating (0% score) - 0 votes


API an Interface to Application’s Programming

We are always overwhelmed by so many Candy Crush Request on Facebook. But how Candy Crush sends its invite to you through Facebook. How Candy Crush knows you are on Facebook. How can Facebook allow any app to access your data without your physical intervention? Here’s the answer:

Suppose I have a Candy Crush app and I want to put my latest scores on Facebook.

How do I do it? There are two ways:

  1. I should hire a person who takes my latest score and posts it on facebook on my behalf. This is a ridiculous and a cumbersome way.

  2. I should use a digital person. API is that digital person, who takes your score and uses Facebook API to posts your scores on Facebook on your behalf. So, now you know that Candy Crush takes your data (if authorized) using Facebook API and sends you an invite to your friends.


Another question arise is what will happen if there is no API and I want to show latest tweets of Apple Corporation on my web page:

  1. I should parse twitter page of Apple Corporation. If twitter changes its look and DOM structure, my web page parser will stop working and I also need to change my parser. This will be over burden.
  2. With an API, the exact structure of request and response is documented upfront by, and is likely to remain constant, regardless of whether the website changes its look and feel for human visitors.

Login via fb or google


When we use LOGIN VIA FACEBOOK OR GOOGLE, to log into different websites, we use their API’S

Now you all must have heard that API is stateless. This means there is no client context being stored on server side or in simple words there are no sessions.

Why API’s are stateless OR Why there are no Sessions ?

ST in REST means State Transfer, which means to transfer state from client to server in every request. This is the only way to scale to millions of concurrent users. It’s easier to distribute a stateless application across load-balanced servers. A stateless application is also easy to cache.



Examples of known API’s around us:


    Now google maps has an API, which is used by cab services to show cab on Google Maps. Without Google Maps API, both these companies have to make their own maps which is extremely difficult

  2. YouTube APIs

Google’s APIs lets developers integrate YouTube videos and functionality into websites or applications. YouTube APIs include the YouTube Analytics API, YouTube Data API, YouTube Live Streaming API, YouTube Player APIs and others

We are surrounded by API’S and I literally mean this

What happens when we want to print a document : Microsoft Word asks the active printer to return its status. Microsoft Word does not care what kind of printer is available. The API worries about that.

Even the simple copy and paste feature uses API. When we copy and paste anything in computer, the program uses API provided by O.S. to work

Two Most Famous Types of API



REST stands for REpresentational State Transfer SOAP stands for Simple Object Access Protocol

Rest is flexible and not bound by so much rules. It is an architectural style rather than a protocol

Made by microsoft, Soap is more rigid set of rules and regulations

Everything is mostly embed in URL, however there may be cases where addiditional information is required to pass.
URL is made of nouns and four verbs are used GET, POST, PUT, DELETE… On the basis of these verbs, program decides which function to perform
GET: It is used when we want to retrieve some data, for ex: Get the recipe of cake id 31.
Optional Params can also be provided like headers
POST: It is used to insert some data in the database, for ex: POST
POSTParams: Id: 1, Name: HotChocolate
PUT: It is used to update some data in the database
Params: Name: Chocolava
DELETE: It is used to delete some data in the database

You must make XML for even the simplest task.

With SOAP in JavaScript means writing a ton of code to perform extremely simple tasks because you must create the required XML structure absolutely every time.

REST requires use of HTTP

Language, platform, and transport independent

Efficient: REST can use smaller message formats

Inefficient: SOAP uses XML for all messages


Which API to use clearly depends on the use Case, but because of ease of use, REST is the most commonly used form of API all over the world

In we use API’s extensively, such as

  • Job details API : It gives us details of a job given its job-id. An example is given below

Mandatory Parameters
JobId : 
for example : 2019348237

Mandatory Headers
clientId :
	abc or xyz

Optional Headers 		 	 	
Accept: application/json OR application/xml	 	 	
Authorization: NAUKRI id=,authsource=(Eg. NAUKRI	 	 	

You can get full list of headers on Headers-Wikipedia

GET Request :

Sample Response:
	"Job": {
	"JobId": "20137",
	"FunctionalArea": "Banking ",
	"Location": "Alexandria - Egypt",
	"Description": "Sales Manager",
	"Designation": "sales manager",
	"LogoUrl": "",
	"TELogoUrl": "",
	"Company": {
	"Name": "ABC",
	"Profile": "917"
  • JobSearch/SRP API : It returns job details given atleast a single keyword or location. Sample response is given below
  • Similar Jobs API : Provides similar jobs, given a Job-Id. Sample response is given below

And many more such as Job recommendations API, Job recommendations count API, Cluster API.

How to make a simple REST API In PHP

Construct an Abstract Class

This class will act as a wrapper for all of the custom endpoints that our API will be using. It means

  1. it must be able to take in our request
  2. grab the endpoint from the URI string
  3. detect the HTTP method (GET, POST, PUT, DELETE)
  4. assemble any additional data provided in the header or in the URI

Once that’s done, the abstract class will pass the request information on to a method in the concrete class to actually perform the work

Creating a Concrete Class

abstract class API
     * Property: method
     * The HTTP method this request was made in, either GET, POST, PUT or DELETE
    protected $method = '';
     * Property: endpoint
     * The Model requested in the URI. eg: /files
    protected $endpoint = '';
     * Property: verb
     * An optional additional descriptor about the endpoint, used for things that can
     * not be handled by the basic methods. eg: /files/process
    protected $verb = '';
     * Property: args
     * Any additional URI components after the endpoint and verb have been removed, in our
     * case, an integer ID for the resource. eg: ////
     * or //
    protected $args = Array();
     * Property: file
     * Stores the input of the PUT request
     protected $file = Null;

    public function __construct($request) {
        $this->args = explode('/', rtrim($request, '/'));
        $this->endpoint = array_shift($this->args);
        if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) {
            $this->verb = array_shift($this->args);

        $this->method = $_SERVER['REQUEST_METHOD'];
        if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
            if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
                $this->method = 'DELETE';
            } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
                $this->method = 'PUT';
            } else {
                throw new Exception("Unexpected Header");

        switch($this->method) {
        case 'DELETE':
        case 'POST':
            $this->request = $this->performSomething($_POST);
        case 'GET':
            $this->request = $this->performSomething($_GET);
        case 'PUT':
            $this->request = $this->performSomething($_GET);
            $this->file = file_get_contents("php://input");
            $this->_response('Invalid Method', 405);
try {
    $API = new MyAPI($_REQUEST['request'], $_SERVER['HTTP_ORIGIN']);
    echo $API->processAPI();
} catch (Exception $e) {
    echo json_encode(Array('error' => $e->getMessage()));

 If you want to know more about how we use APIs in our engineering projects, drop a comment below.

9 thoughts on “Rest API

  1. A very well written blog and it is really intuitive for anyone even with no experience to get what you want to convey.

    I would appreciate if the demo links like getting recipe for cake are working. That gives user a good feel.

    Keep up the good work guys.

  2. Hi,

    Ton of users creates alerts in naukri when new job gets added how is the alert system working is it a btach or realtime if real whats technologies i should use

  3. Do you use any PHP framework to write API’s. If so, please explain a little about it in your next blog.

  4. I didn’t know that even a simple copy paste operation on my Laptop also use API to work. Thanks for giving this primary knowledge to me. After reading this article, API is no more a geek to me

Comments are closed.