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.
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.
Source: Stackoverflow.com