{"id":10845,"date":"2017-05-24T23:56:55","date_gmt":"2017-05-24T21:56:55","guid":{"rendered":"http:\/\/flaven.fr\/?p=10845"},"modified":"2017-05-25T13:38:17","modified_gmt":"2017-05-25T11:38:17","slug":"proof-of-concept-to-create-a-small-rest-api-with-slim-the-minimalist-php-framework","status":"publish","type":"post","link":"https:\/\/flaven.fr\/2017\/05\/proof-of-concept-to-create-a-small-rest-api-with-slim-the-minimalist-php-framework\/","title":{"rendered":"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework"},"content":{"rendered":"<p>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 +.<br \/>\nSome examples work, some others don&#8217;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.<br \/>\nI finally discover 3 of the likely sources of all these so-called articles.<br \/>\nI have called them &#8220;the supposed source of the Nile&#8221;.<\/p>\n<ol>\n<li><a href=\"https:\/\/www.simplifiedcoding.net\/php-restful-api-framework-slim-tutorial-1\/\" target=\"_blank\">Simplified Coding &#8211; PHP Restful API Framework SLIM to Create REST API \u2013 1<\/a><\/li>\n<li><a href=\"http:\/\/ericbrandel.com\/2013\/01\/18\/quickly-build-restful-apis-in-php-with-slim-part-3\/\" target=\"_blank\">Eric Brandel &#8211; Quickly Build RESTful APIs in PHP with Slim \u2013 Part 3<\/a><\/li>\n<li><a href=\"http:\/\/www.codediesel.com\/php\/create-a-quick-rest-api-using-slim-framework\/\" target=\"_blank\">Codediesel &#8211; Create a quick REST API using Slim framework<\/a><\/li>\n<\/ol>\n<p>To this short-list, I will add 2 more resources.<\/p>\n<p>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.<\/p>\n<ul>\n<li> AndroidHive &#8211; How to create REST API for Android app using PHP, Slim and MySQL \u2013 Day 2\/2<br \/><a href=\"http:\/\/www.androidhive.info\/2014\/01\/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23\/\" target=\"_blank\">http:\/\/www.androidhive.info\/2014\/01\/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23\/<\/a><\/li>\n<\/ul>\n<p>My purpose was to rapidly build up an POC of an API with the help of MySQL. &#8220;No flesh and blood, not fat&#8221;, just pure representation that can be reused as much as I want on any subject.<br \/>\nIf I want to make an API on street art, on wines or on managing translations in 14 languages, that what I wanted.<\/p>\n<p>So, I have avoided authentication issue. Too big for me, I am too lazy.<\/p>\n<p>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 \ud83d\ude42 but is was inspiring.<\/p>\n<ul>\n<li>RESTful services with jQuery, PHP and the Slim Framework<br \/><a href=\"http:\/\/coenraets.org\/blog\/2011\/12\/restful-services-with-jquery-php-and-the-slim-framework\/\" target=\"_blank\">http:\/\/coenraets.org\/blog\/2011\/12\/restful-services-with-jquery-php-and-the-slim-framework\/<\/a><\/li>\n<\/ul>\n<p>Enough reading, let&#8217;s start to give my own &#8220;rudimentary&#8221; version of an API.<\/p>\n<h4>A. The &#8220;rudimentary&#8221; API, the code explained<\/h4>\n<p><b>You can find out the code @bflaven on <a href=\"https:\/\/github.com\/bflaven\/BlogArticlesExamples\/tree\/master\/poc_api_slim\" target=\"_blank\">https:\/\/github.com\/bflaven\/BlogArticlesExamples\/tree\/master\/poc_api_slim<\/a><\/b><\/p>\n<p><b>1. REQUIRE &#8211; The &#8220;rudimentary&#8221; API<\/b><br \/>\nFor sure, you need the framework and declare the instance  of the app.<\/p>\n<pre lang=\"php\">\r\n\r\n\/**\r\n * ----------- REQUIRE\r\n---------------------------------\r\n *\/\r\n\r\nrequire 'Slim\/Slim.php';\r\nuse Slim\\Slim;\r\nSlim::registerAutoloader();\r\n$app = new Slim();\r\n\r\n<\/pre>\n<p><b>The .htaccess has to put in the directory of the API eg \/Applications\/MAMP\/htdocs\/api-for-mobile\/api-v3\/<\/b><\/p>\n<pre lang=\"text\">\r\nRewriteEngine On\r\nRewriteCond %{REQUEST_FILENAME} !-f\r\nRewriteRule ^ index.php [QSA,L]\r\n<\/pre>\n<p><b>2. MESSAGES &#8211; The &#8220;rudimentary&#8221; API<\/b><br \/>\nVery cheesy way to pretend you have build up a true API without handling the HTTP status codes properly and instead using a \u201carchaic\u201d error messages system. I have made this heresy in plain consciousness because I like to get answer in browser and not only in postman.<\/p>\n<pre lang=\"php\">\r\n\/**\r\n * ----------- MESSAGES\r\n---------------------------------\r\n *\/\r\ndefine ('_MESSAGE_ERROR_NO_RECORD_FOUND_','{\"error\": {\"text\": \"no record found\"}}');\r\ndefine ('_MESSAGE_ERROR_DELETE_','{\"error\": {\"success\": \"delete succeeded\"}}');\r\ndefine ('_MESSAGE_ADD_RECORD_SUCCEEDED_', '{\"success\": {\"success\": \"record successfully added\"}}');\r\ndefine ('_MESSAGE_UPDATE_RECORD_SUCCEEDED_', '{\"success\": {\"success\": \"record successfully updated\"}}');\r\n<\/pre>\n<p><b>3. ROUTES &#8211; The &#8220;rudimentary&#8221; API<\/b><br \/>\n<b>2 good practices when you write routes<\/b><\/p>\n<ol>\n<li>Centralize the routes of your API and use functions. Functions are always much more self explanatory than a poor routes list.<\/li>\n<li>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.<\/li>\n<\/ol>\n<pre lang=\"php\">\r\n\/**\r\n * ----------- ROUTES\r\n---------------------------------\r\n *\/\r\n\/* homepage *\/\r\n$app->get('\/', 'getIntroHelp');\r\n\r\n\/* All the get operation *\/\r\n$app->get('\/strings', 'getStrings');\r\n$app->get('\/strings\/:id', 'getStringDetails');\r\n$app->get('\/strings\/search\/:query', 'findByStringName');\r\n\/* Add a string  *\/\r\n$app->post('\/strings', 'addString');\r\n\/* Update a string  *\/\r\n$app->put('\/strings\/:id', 'updateString');\r\n\/* Delete a string  *\/\r\n$app->delete('\/strings\/:id', 'deleteString');\r\n\r\n\/* required *\/\r\n$app->run();\r\n<\/pre>\n<p><b>4. FUNCTIONS &#8211; The &#8220;rudimentary&#8221; API<\/b><br \/>\nHere is the list of the functions. I know it may be stupid, but I like having a welcome page. 2 reasons to this : <\/p>\n<ol>\n<li>To have the sensation that the API is truly up and running<\/li>\n<li>To leverage on this page to help users to manipulate your API right away for the very first operations&#8230;<\/li>\n<\/ol>\n<pre lang=\"php\">\r\n  \/**\r\n * ----------- FUNCTIONS\r\n---------------------------------\r\n *\/\r\n\/**\r\n * Welcome\r\n * url - \/\r\n * method - GET\r\n * description - the main documentation\r\n *\/\r\nfunction getIntroHelp() {    \r\n    $intro = '{\r\n    \"name\": \"POC API\",\r\n    \"description\": \"WELCOME ON SLIM FAST API V1\",\r\n    \"interactions\": {\r\n        \"listing_strings\": {\r\n            \"url\": \"\/strings\",            \r\n            \"method\": \"GET\",\r\n            \"parameters\": \"n\/a\",\r\n            \"required\": [\"n\/a\"],\r\n            \"description\": \"Listing of the strings\"\r\n        },\r\n        \"details_string\": {\r\n            \"url\": \"\/strings\",         \r\n            \"method\": \"GET\",\r\n            \"parameters\": \"id\",\r\n            \"required\": [\"id\"],\r\n            \"description\": \"Get the details of a string\"\r\n        },\r\n        \"add_string\": {\r\n            \"url\": \"\/strings\",         \r\n            \"method\": \"POST\",\r\n            \"parameters\": \"brand, source, language, cat, string_name, string_name_model, string_name_value\",\r\n            \"required\": [\"brand\", \"source\", \"language\", \"cat\", \"string_name\", \"string_name_model\", \"string_name_value\"],\r\n            \"description\": \"Add a new string\"\r\n        },\r\n        \"update_string\": {\r\n            \"url\": \"\/strings\",         \r\n            \"method\": \"PUT\",\r\n            \"parameters\": \"id\",\r\n            \"required\": [\"id\"],\r\n            \"description\": \"Update an existing string\"\r\n        },\r\n        \"delete_string\": {\r\n            \"url\": \"\/strings\/:id\",         \r\n            \"method\": \"DELETE\",\r\n            \"parameters\": \"id\",\r\n            \"required\": [\"id\"],\r\n            \"description\": \"To delete a string in the database\"\r\n        },\r\n        \"search_string\": {\r\n            \"url\": \"\/strings\/search\/:query\",         \r\n            \"method\": \"GET\",\r\n            \"parameters\": \"query\",\r\n            \"required\": [\"query\"],\r\n            \"description\": \"To search a string in the database on string_name with UPPER(RTRIM(string_name)) eg twitter_\"\r\n        }\r\n    }\r\n}';\r\n        echo ($intro);\r\n}\r\n<\/pre>\n<p><b>5. extra informations about The &#8220;rudimentary&#8221; API &#8211; Test for emptiness<\/b><br \/>\nI know it is quick and very dirty but who care? It is part of the &#8220;cheesy smoke screen conspiracy&#8221; to pretend that you have made a true API even to your own eyes. <\/p>\n<p><b>If there is no result, please tell me what I did wrong<\/b><\/p>\n<pre lang=\"php\">\r\n\r\n\t\/* emptiness *\/\r\n        if(!$string) {\r\n                echo (''._ERROR_MESSAGE_UPDATE_FAILED_.''); \r\n        } else {\r\n                echo json_encode($string);            \r\n        }\r\n        \/* emptiness *\/\r\n<\/pre>\n<h4>B. The &#8220;rudimentary&#8221; API &#8211; send content to this API<\/h4>\n<p>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.<\/p>\n<p><b>That is reason I have given the Postman collection of basic queries.<\/b><\/p>\n<p><b>See all the queries in my-api-from-me-see-api-v3.postman_collection.json<\/b><\/p>\n<p><b>Create a string<\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_4.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<p><b>Update a string<\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_6.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<p><b>Delete a string<\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_7.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<p><b>Search for the query string <code>twitter_<\/code><\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_8.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<h4>Few screens of the output in JSON<\/h4>\n<p><b>The welcome page @<code>\/<\/code><\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_1.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<p><b>Listing of the strings (getStrings) @<code>\/strings<\/code><\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_2.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<p><b>Listing of the details of one string (getStringDetails) @<code>\/strings<\/code><\/b><br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"aligncenter\" src=\"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_3.jpg\" width=\"640\" height=\"480\" alt=\"Proof of concept to create a small Rest API with Slim, the minimalist PHP framework\"><\/p>\n<h2>En savoir plus<\/h2>\n<ul>\n<li>Creating A Simple REST API With Slim Framework<br \/><a href=\"https:\/\/www.cloudways.com\/blog\/simple-rest-api-with-slim-micro-framework\/\" target=\"_blank\">https:\/\/www.cloudways.com\/blog\/simple-rest-api-with-slim-micro-framework\/<\/a><\/li>\n<li>How to Create a Simple REST API With Slim Framework<br \/><a href=\"http:\/\/phpflow.com\/php\/create-simple-rest-api-using-slim-framework\/\" target=\"_blank\">http:\/\/phpflow.com\/php\/create-simple-rest-api-using-slim-framework\/<\/a><\/li>\n<li>Getting Started with Slim Framework &#8211; Creating a RESTful API<br \/><a href=\"http:\/\/codoki.com\/2015\/01\/27\/getting-started-with-slim-framework\/\n\" target=\"_blank\">http:\/\/codoki.com\/2015\/01\/27\/getting-started-with-slim-framework\/<br \/>\n<\/a><\/li>\n<li>Create REST applications with the Slim micro-framework<br \/><a href=\"https:\/\/www.ibm.com\/developerworks\/library\/x-slim-rest\/\" target=\"_blank\">https:\/\/www.ibm.com\/developerworks\/library\/x-slim-rest\/<\/a><\/li>\n<li>How to Create a Simple REST API With Slim Framework<br \/><a href=\"http:\/\/phpflow.com\/php\/create-simple-rest-api-using-slim-framework\/\" target=\"_blank\">http:\/\/phpflow.com\/php\/create-simple-rest-api-using-slim-framework\/<\/a><\/li>\n<li>AndroidHive &#8211; Android Task Manager App REST Api Testing<br \/><a href=\"https:\/\/www.youtube.com\/watch?v=CJcf-Zn9oRI\" target=\"_blank\">https:\/\/www.youtube.com\/watch?v=CJcf-Zn9oRI<\/a><\/li>\n<li>Creating a RESTful API using Slim php framework<br \/><a href=\"https:\/\/spinspire.com\/article\/creating-restful-api-using-slim-php-framework\" target=\"_blank\">https:\/\/spinspire.com\/article\/creating-restful-api-using-slim-php-framework<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>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&hellip; <\/p>\n<p class=\"text-center\"><a href=\"https:\/\/flaven.fr\/2017\/05\/proof-of-concept-to-create-a-small-rest-api-with-slim-the-minimalist-php-framework\/\" class=\"more-link\">Continue reading &rarr; <span class=\"screen-reader-text\">Proof of concept to create a small Rest API with Slim, the minimalist PHP framework<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":10854,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"bf_ai_meta_description":"Build a small REST API with Slim, the minimalist PHP framework. Find reliable tools and outcomes for your proof of concept.","bf_ai_og_title":"Create REST API with Slim","footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[3439,3437,3442,3444,3447,3448,3449,3450,3435],"tags":[2194,2183,2386,31,2388,20,2387,2182,475,2375],"class_list":["post-10845","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-apis-integration","category-business-case-studies","category-mobile-devices","category-programming-databases","category-technology-trends","category-tools-productivity","category-tutorials-how-to","category-ux-product-design","category-web-development","tag-agile","tag-api","tag-dry","tag-mobile","tag-mvp","tag-php","tag-poc","tag-web","tag-wireframe","tag-workflow"],"jetpack_publicize_connections":[],"jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p3Vuhl-2OV","jetpack_featured_media_url":"https:\/\/flaven.fr\/wp-content\/uploads\/2017\/05\/poc_api_slim_b.jpg","_links":{"self":[{"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/posts\/10845","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/comments?post=10845"}],"version-history":[{"count":15,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/posts\/10845\/revisions"}],"predecessor-version":[{"id":10869,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/posts\/10845\/revisions\/10869"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/media\/10854"}],"wp:attachment":[{"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/media?parent=10845"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/categories?post=10845"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/flaven.fr\/happy-api\/wp\/v2\/tags?post=10845"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}