Main navigation

Creating a RESTful API using Slim php framework

Christian Crawford

Friday, November 7, 2014 - 09:23

Restful architectures are often used to create client/server network environments. REST, which stands for representational state transfer, is a simpler alternative to SOAP and WSDL services, but still maintains great features like platform-independence and language independence. REST services explicitly use HTTP methods when implementing their calls, therefore any good API should support the basic GET, POST, PUT, and DELETE methods. Along with knowing the HTTP methods you must understand the HTTP status codes as well. If you are unfamiliar with what the various codes mean you can read about them here .

For this article we will be using the slim PHP micro framework to implement the RESTful API. Slim was chosen because it is very light weight, clean, supports all the HTTP methods, and also provides support for middleware layers. Along with slim you will need a web server (apache or nginx), PHP, and MySQL installed before proceeding. Once you’ve gotten all the necessary files you can begin.

You must begin the PHP script by including the slim libraries

require 'Slim/Slim.php';

Next you will create a new instance of your app and define the routes that you will be using

This function creates a new entry for the new users in our database. The values being passed into the SQL query are being bound in lines 9 and 10 and that information comes from the request body (line 4).

Once you’ve gotten you all the code written you can now test your API to make sure that you code is returning the correct information and doing the desired actions. You can test them by opening your preferred shell and running the following cURL commands