5 minutes reading time (941 words)

Writing Mock APIs in PHP

Writing Mock APIs in PHP

Many a times we could land up in situation when web services for some functionality are not ready. At that time creating desired JSON and accessing it by Mock API will be a good option, so that when web service is ready you can make little changes in your code. In this post let’s see how to write Mock APIs.

Before proceeding to write Mock APIs, you must be aware of following concepts

JSON

JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.

JSON is the most widely used format for interchanging data on the web. For more detail about JSON refer http://www.w3schools.com/json/

API

API, an abbreviation of application program interface, is a set of routines, protocols, and tools for building software applications. The API specifies how software components should interact and are used when programming graphical user interface (GUI) components.  A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

In practice, many times an API comes in the form of a library that includes specifications for routines, data structures, object classes, and variables. In some other cases, notably for SOAP and REST services, an API comes as just a specification of remote calls exposed to the API consumers.

Web API

The general concept of a web API (application programming interface) has two main interpretations. It is used to refer to both a server-side API upon a web server as well as client-side API within a web browser.

Server Side

A server-side web API is a programmatic interface to a defined request-response message system, typically expressed in JSON or XML, which is exposed via the web—most commonly by means of an HTTP-based web server. Mashups are web applications which combine the use of multiple such web APIs

While "Web API" in this context is sometimes considered a synonym for web service, 

Web 2.0 web applications have moved away from SOAP-based web services towards more cohesive collections of RESTful web resources. These RESTful web APIs are accessible via standard HTTP methods by a variety of HTTP clients including browsers and mobile devices.

Client Side

A client-side web API is a programmatic interface to extend functionality within a web browser or other HTTP client. Originally these were most commonly in the form of native plug-in architectures however most newer ones target standardized JavaScript bindings.

Web API Features

  • It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  • Responses have an Accept header and HTTP status code.
  • Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  • It may accepts and generates the content which may not be the object oriented like images, PDF files etc.
  • It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  • It can be hosted within the application or on IIS.
  • It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.

PHP

PHP is a server scripting language, and is a powerful tool for making dynamic and interactive Web pages quickly.

What is a PHP File?

  • PHP files can contain text, HTML, CSS, JavaScript, and PHP code
  • PHP code are executed on the server, and the result is returned to the browser as plain HTML
  • PHP files have extension ".php"

What Can PHP Do?

  • PHP can generate dynamic page content
  • PHP can create, open, read, write, delete, and close files on the server
  • PHP can collect form data
  • PHP can send and receive cookies
  • PHP can add, delete, modify data in your database
  • PHP can restrict users to access some pages on your website
  • PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output any text, such as XHTML and XML.

You must be aware of basic PHP programming. For more information about PHP refer http://www.w3schools.com/php/default.asp

Steps To Create Mock API

You must be very clear of request parameters and the response object before following these steps. Response may be in JSON or XML. Here I am considering we need response in JSON format.

1]  Create JSON file which contains the response. For example, login.json file contain following

{
    key: "65307d22a47230270f0bbc4d1c9cffb4",
    uid: 4
} 

2]  Create index.php file containing following

<?php 
    $api = (isset($_GET['api']))?$_GET['api']:''; 
    $uname = (isset($_GET['uname']))?$_GET['uname']:''; 
    header('Content-Type: application/json'); 

    if (!$api) { 
        $err = new stdClass; $err->code = 404; 
        $err->message = 'API Not found'; 
        echo json_encode($err); return; 
    } 
    
    $basefile = dirname(__FILE__). '/'.$api.'.json'; 
    if (file_exists($basefile)) { 
        echo file_get_contents($loadfile1); 
    } 
    else { 
        $err = new stdClass; 
        $err->code = 404; 
        $err->message = 'Invalid File’; 
        echo json_encode($err); return; 
    } 
?> 

3]  Save both these files at same level on server. Call the index.php file, pass the parameters in url if GET method is used or pass them in object if POST method is used.

Give the respective name of variable that we are referencing in PHP file. In above example, we are referencing variables “api” and “uname”. Hence api call will be like

http://mahesh.tekdi.net/easysocialapi/index.php?api=login&amp;uname=mahesh

If you want to pass more than one variable pass the variables by appending names by “&”. Add multiple conditions in index.php file to handle other requests as per your need.

That’s it for Mock API. Wish you best luck for creating Mock APIs. :)

Easysocial App 5.3 Beta 1 is Here!
LocalStorage Rocks…!