Creating a REST API with PHP

I am creating my first API, for which, if two values ​​are passed, I should get a response in JSON format. The number will be passed as POST parameters. You can use either cURL or some POST method.

Despite the fact that it is very simple, I would like to know the best practices, and the API should be created based on the controller model. Not just PHP.

I have Googled for many REST API tutorials. They were good, and I gained some knowledge about it.

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

If you ask me what I tried, it would be a lot of fun as a beginner, all I could do was 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 to get a response from the REST API as JSON. I also have to check it using the REST console to get a standard answer.

Please provide me with a very simple but still standard RESTful API.

+47
json rest api php curl
Feb 22 '14 at 19:26
source share
2 answers

In your example, this is fine as it is: its simple and works. The only thing Id offers:

  • POSTed data verification
  • make sure your API sends a Content-Type header to tell the client to expect a JSON response:

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

In addition, an API is what accepts input and provides output. You can "overdo it" because you make things more complicated than necessary.

If you want to go down the route of controllers and models, read the GitHub that deserve attention.

+69
Feb 22 '14 at 19:38
source share

Trying to write a REST API from scratch is no easy task. There are many factors to consider, and you will need to write a lot of code to process requests and data from the caller, authenticate, search for data, and send responses.

It’s best to use a framework that already has this functionality, ready and tested for you.

Some suggestions:

Phalcon - Creating a REST API - Easy to use all in one structure with tremendous performance

Apigility - One size fits all Zend Technologies API Processing Platform

Laravel API Tutorial

and much more. A simple search on Bitbucket / Github will give you plenty of resources to get you started.

+18
Feb 22 '14 at 19:39
source share



All Articles