Proof of concept to create a small Rest API with Slim, the minimalist PHP framework
I have looked for many resources throughout the web to find out a small and easy piece of PHP to create a POC for an API. Naturally, I was led to find several sites where you can grab examples made mostly with Slim 2.0 and +.
Some examples work, some others don’t. The reason is simple : plagiarism, mostly due to copy of copy of copy from one source with a progressive loss of meaning and understanding.
I finally discover 3 of the likely sources of all these so-called articles.
I have called them “the supposed source of the Nile”.
- Simplified Coding – PHP Restful API Framework SLIM to Create REST API – 1
- Eric Brandel – Quickly Build RESTful APIs in PHP with Slim – Part 3
- Codediesel – Create a quick REST API using Slim framework
To this short-list, I will add 2 more resources.
There is one article written by AndroidHive. The logic that prevailed for this POC is nice, nevertheless I consider it too development oriented, not enough user friendly for a dummy developer like me.
- AndroidHive – How to create REST API for Android app using PHP, Slim and MySQL – Day 2/2
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/
My purpose was to rapidly build up an POC of an API with the help of MySQL. “No flesh and blood, not fat”, just pure representation that can be reused as much as I want on any subject.
If I want to make an API on street art, on wines or on managing translations in 14 languages, that what I wanted.
So, I have avoided authentication issue. Too big for me, I am too lazy.
For the wines, it has been already made but unfortunately, the project did not work anymore when I have migrate it from PC to MAC. So I found it better to start with a fresh code 🙂 but is was inspiring.
- RESTful services with jQuery, PHP and the Slim Framework
http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/
Enough reading, let’s start to give my own “rudimentary” version of an API.
A. The “rudimentary” API, the code explained
You can find out the code @bflaven on https://github.com/bflaven/BlogArticlesExamples/tree/master/poc_api_slim
1. REQUIRE – The “rudimentary” API
For sure, you need the framework and declare the instance of the app.
/** * ----------- REQUIRE --------------------------------- */ require 'Slim/Slim.php'; use Slim\Slim; Slim::registerAutoloader(); $app = new Slim(); |
The .htaccess has to put in the directory of the API eg /Applications/MAMP/htdocs/api-for-mobile/api-v3/
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [QSA,L] |
2. MESSAGES – The “rudimentary” API
Very cheesy way to pretend you have build up a true API without handling the HTTP status codes properly and instead using a “archaic” error messages system. I have made this heresy in plain consciousness because I like to get answer in browser and not only in postman.
/** * ----------- MESSAGES --------------------------------- */ define ('_MESSAGE_ERROR_NO_RECORD_FOUND_','{"error": {"text": "no record found"}}'); define ('_MESSAGE_ERROR_DELETE_','{"error": {"success": "delete succeeded"}}'); define ('_MESSAGE_ADD_RECORD_SUCCEEDED_', '{"success": {"success": "record successfully added"}}'); define ('_MESSAGE_UPDATE_RECORD_SUCCEEDED_', '{"success": {"success": "record successfully updated"}}'); |
3. ROUTES – The “rudimentary” API
2 good practices when you write routes
- Centralize the routes of your API and use functions. Functions are always much more self explanatory than a poor routes list.
- Use comment as often as you can because from day to day, you will forget the meaning of your function. Be simple and straightforward in your comment and always have in mind that your code may be read by someone else.
/** * ----------- ROUTES --------------------------------- */ /* homepage */ $app->get('/', 'getIntroHelp'); /* All the get operation */ $app->get('/strings', 'getStrings'); $app->get('/strings/:id', 'getStringDetails'); $app->get('/strings/search/:query', 'findByStringName'); /* Add a string */ $app->post('/strings', 'addString'); /* Update a string */ $app->put('/strings/:id', 'updateString'); /* Delete a string */ $app->delete('/strings/:id', 'deleteString'); /* required */ $app->run(); |
4. FUNCTIONS – The “rudimentary” API
Here is the list of the functions. I know it may be stupid, but I like having a welcome page. 2 reasons to this :
- To have the sensation that the API is truly up and running
- To leverage on this page to help users to manipulate your API right away for the very first operations…
/** * ----------- FUNCTIONS --------------------------------- */ /** * Welcome * url - / * method - GET * description - the main documentation */ function getIntroHelp() { $intro = '{ "name": "POC API", "description": "WELCOME ON SLIM FAST API V1", "interactions": { "listing_strings": { "url": "/strings", "method": "GET", "parameters": "n/a", "required": ["n/a"], "description": "Listing of the strings" }, "details_string": { "url": "/strings", "method": "GET", "parameters": "id", "required": ["id"], "description": "Get the details of a string" }, "add_string": { "url": "/strings", "method": "POST", "parameters": "brand, source, language, cat, string_name, string_name_model, string_name_value", "required": ["brand", "source", "language", "cat", "string_name", "string_name_model", "string_name_value"], "description": "Add a new string" }, "update_string": { "url": "/strings", "method": "PUT", "parameters": "id", "required": ["id"], "description": "Update an existing string" }, "delete_string": { "url": "/strings/:id", "method": "DELETE", "parameters": "id", "required": ["id"], "description": "To delete a string in the database" }, "search_string": { "url": "/strings/search/:query", "method": "GET", "parameters": "query", "required": ["query"], "description": "To search a string in the database on string_name with UPPER(RTRIM(string_name)) eg twitter_" } } }'; echo ($intro); } |
5. extra informations about The “rudimentary” API – Test for emptiness
I know it is quick and very dirty but who care? It is part of the “cheesy smoke screen conspiracy” to pretend that you have made a true API even to your own eyes.
If there is no result, please tell me what I did wrong
/* emptiness */ if(!$string) { echo (''._ERROR_MESSAGE_UPDATE_FAILED_.''); } else { echo json_encode($string); } /* emptiness */ |
B. The “rudimentary” API – send content to this API
Most of the time, you can spend hours to find out how to send content to your brand new API and many of the articles that I have read supposed you are mastering Postman and if it is not the case, you will be forced to make time-consuming iterations to populate data in your API.
That is reason I have given the Postman collection of basic queries.
See all the queries in my-api-from-me-see-api-v3.postman_collection.json
Create a string
Update a string
Delete a string
Search for the query string twitter_
Few screens of the output in JSON
The welcome page @/
Listing of the strings (getStrings) @/strings
Listing of the details of one string (getStringDetails) @/strings
En savoir plus
- Creating A Simple REST API With Slim Framework
https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/ - How to Create a Simple REST API With Slim Framework
http://phpflow.com/php/create-simple-rest-api-using-slim-framework/ - Getting Started with Slim Framework – Creating a RESTful API
http://codoki.com/2015/01/27/getting-started-with-slim-framework/
- Create REST applications with the Slim micro-framework
https://www.ibm.com/developerworks/library/x-slim-rest/ - How to Create a Simple REST API With Slim Framework
http://phpflow.com/php/create-simple-rest-api-using-slim-framework/ - AndroidHive – Android Task Manager App REST Api Testing
https://www.youtube.com/watch?v=CJcf-Zn9oRI - Creating a RESTful API using Slim php framework
https://spinspire.com/article/creating-restful-api-using-slim-php-framework