© 2013 All rights reserved.
1

PHP HOW TO: create server API

In one my project, i need to be able to connect to and communicate with the server and use some of its features. I had to create a simple API that will be used for communication. This is my simple solution, how to create API.


api

 

Requirements

 

The main requirements were:

  • easy to use
  • easily expandable
  • exchange data using json

My application is written in PHP (NETTE framework), but the sample is easily copied to another platform.

 

How to call api

 

I used a JSON in which I define all. I define the method which you want to call, and the data that I want to pass to the api. My JSON looks like this:

This JSON define method with name “myMethodName” which i want call, and two params, which i need set into this method.

Api will be called very simply as follows:

Result from API

All methods api will have the same result. The return value is again JSON. Always will contain information about the error and the result. The structure will be as follows:

  • Error – true|false value. If an error occurs, it will be true
  • Message – If an error occurs, the message will be added into result
  • Data – In case of success, contains data

In the previous example we can add following code:

 

Create API class

 

First, we define class and methods that will return results. We can do this as follows:

Methods _setError() and _setSuccess() will call in case of success or failure. The method terminate () is called whenever api end. The method returns the result to the OUTPUT.

Now we can create a constructor that calls method defined in JSON. In my case I use function with name startup(), which is used in Nette.

Function converts the input data to JSON object. Next checks whether a called method exists, and if so, it starts this method.

Finaly we can write first API method (this code is only example):

 

Recap solution

 

Finally, a whole class, which contains one API method

Comments are closed for this page

Miroslav Koula

Seems to be working and fine. I would just think to use some standards like: http://www.jsonrpc.org/specification – what I see you’re very close.

The difference is in json {“method”: “methodName”, “params”: {“param1”: “value1”, …}} – small difference, but more complex is nice to have it in associative array probably… But my point of view…

For example, by using reflection you can easily test if the parameters are correct for the called method…

About
Hi, i am programmer from the Czech Republic. I love web development (Ruby, Ruby on Rails, PHP, Nette) and iOS development (Objective-C, Cocoa).
To cooperate, here is my phone:
+420 608 836