Home » Php » json – Creating a REST API using PHP

json – Creating a REST API using PHP

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m creating my first API to which if two values are passed, I should get the response in the JSON format. The number will be passed as parameters by POST. Either using cURL or whatever POST method is available.

Even though this is a very basic one, I would like to know the best practices and the API should be created by model–controller basis. Not just plain PHP.

I have Googled for many REST API tutorials. They were good and I have acquired some knowledge on it.

But I would like to get a sample model of the code so that I can refer to it and build my own, and that sample of course in the standard practice of making a real REST API.

If you ask me what I have tried, it would be really fun, as a beginner, all I could do is this:

$num1 = $_REQUEST['num1'];
$num2 = $_REQUEST['num2'];

$total = $num1 + $num2;
echo json_encode($total);

Of course this can never be called an API, but still. If I give a POST response to this, I want the response from the REST API as JSON. I should be able to test it by REST console as well so that I get a standard response.

Please do provide me with a very basic but yet a standard RESTful API.

How to&Answers:

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

Answer:

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon – REST API building – Easy to use all in one framework with huge performance

Apigility – A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.