Creating a RESTful API with Slim Framework 3, PHP/MySQl

Slim is a full-featured, open-source PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. It comes with a sophisticated URL dispatcher and middleware architecture that makes it ideal for static websites or API prototyping. It supports all(GET, POST, PUT, DELETE) the HTTP methods.

This article examines Slim in detail, illustrating how you can use it to rapidly build and deploy a REST API with support for authentication and multiple request/response formats.

How to install

If you are using Composer, the PHP dependency manager, simply issue the following command

Replace [my-app-name] with the desired directory name for your new application. The above command will create a project using Slim-Skeleton application and it has below show directory structure.

slim_directories

Now You can run it with PHP’s built-in webserver or you can point your browser with full URL.

So after gone through the above steps, if you point your browser to http://locahost:8080/, you would have following output in the browser –

slim-demo

Database design and table

Name your database whatever you want, and run below shown SQL it will create task table.

Insert some sample data into the tasks table.

Database configuration

Open your src/settings.php file and configure your database setting by adding/editing below showing database config array.

Now open your src/dependencies.php file and configure database library. There are many database libraries available for PHP, but this example uses PDO – this is available in PHP as standard so it’s probably useful in every project, or you can use your own libraries by adapting the examples below.

In the below code we are injecting database object into container using dependicy injection, in this case called db:

We are going to implement following API calls –

Method URL Action
GET /todos Retrieve all todos
GET /todos/search/bug Search for todos with ‘bug’ in their name
GET /todo/1 Retrieve todo with id == 1
POST /todo Add a new todo
PUT /todo/1 Update todo with id == 1
DELETE /todo/1 Delete todo with id == 1

Implementing the API calls with Slim

Now that we have our Slim app up and running with the database connection, we need to manage todos in the database.

Getting the Todos list – We are going to create a new route so that when a user hits /todos, it will return a list of all todos in JSON format. Open your src/routes.php and add

This function simply return all todos information as you can see in this query, to call this API use this URL http://localhost:8080/todos.

Getting single todo – We are going to create a new route so that when a user hits /todo/{id}, it will return a todo in JSON format.

This function check record of given id and return if found anything, to call this API use this URL http://localhost/todo/1.

Find todo by name – We are going to create a new route so that when a user hits /todos/search/{Query}, it will return a list of all matched todos in JSON format.

This function search in database for your given query, to call this API use this URL http://localhost/todos/search/bug

Add todo – We are going to create a new route so that when a user sends a post request to /todo with required data, the app will add a new record to the database.

This API accepts post request and insert submitted data into your database. To call this API use this URL http://localhost/todo

Delete Task – We are going to create a new route so that when a user sends a delete request to /todo/{id}, the app will delete a record from the database.

Update Task – We are going to create a new route so that when a user sends a put request to /todo/{id} with required data, the app will update a record based on match parameter in the database.

This API accept put request and updates submitted data in your database. To call this API use this URL http://localhost/todo/{id}

Here is the the complete final src/routes.php file

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.


  • Haakon Wærstad

    Great tutorial, and it works as expected. The problem i’m facing is the characters æ,ø,å in the norwegian alphabeth. How do I get the right output? Thanks in advance.

  • smaugtheswaggers

    Love the tutorial, but this is more of a intermediate level tutorial. For beginners, it might still be little hard to understand. Before create Rest API, it is important to understand what REST is. Here is a more beginner level tutorial: https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/

    • Thanks for you feedback, I will update the post.

  • Nadim Gouia

    Please why $request->getParsedBody(); return always an empty array, im testing with ‘Advanced Rest Client’ and $input array is always null

    • Select “application/x-www-form-urlencoded” option in your advanced rest client

      • Nadim Gouia

        i did but its still the same

        • Try with curl

          • Try $request->getBody();

  • Does it support CORS?

  • MizAkita

    Great tutorial. I’ve used slim in several applications. I’ve made some fairly robust Ali’s using it at an even easier set up than this.

  • Emira Trabelsi

    how to add jwt to this project ? any idea please ?

  • mash kaponde

    Sorry, this might be pretty basic but am just learning php. I am getting this “Parse error: syntax error, unexpected ‘=>’ (T_DOUBLE_ARROW) in C:xampphtdocssales-apisrcsettings.php on line 3”.

    What could be the problem. Thanks

    • Let me know your php version.

      • mash kaponde

        Hi arjun, my PHP version is 7.0.6

        • I tried code on PHP 7 its working just fine, did you fine fix in your case

          • mash kaponde

            I got it working thanks, Am still not even sure what i did though. But this is really a great tutorial.

  • Simone Pignatelli
    • Muhamad Rizki

      add this to $pdo variable
      charset=utf8;
      so it will be like this:
      $pdo = new PDO(“mysql:host=” . $settings[‘host’] . “;charset=utf8;dbname=” . $settings[‘dbname’], $settings[‘user’], $settings[‘pass’]);

      • If you’re running an older version of PHP(exec(“set names utf8”);

  • Aymane

    It go back this error :
    Static route “/todos” is shadowed by previously defined variable route “/([^/]+)” for method “GET”

    • Order of routes is matter,so keep the static routes before the dynamic ones.

      • Aymane

        thank you but now it turn back this : Method not allowed. Must be one of: PUT

  • Eder Inocêncio Côrtes

    Hi Arjun, good tutorial, very useful.

    Sorry, this might be pretty basic but am just learning about rest app with slim.
    Why you are using $todos = $sth->fetchAll(); after DELETE statement?

  • Eder Inocêncio Côrtes

    My two cents:

    Call API using cURL

    Get all todos
    curl -i -X GET http://localhost/todos

    Get all todos with ‘bug’ in their name:
    curl -i -X GET http://localhost/todos/search/bug

    Get todo #5:
    curl -i -X GET http://localhost/todos/5

    Delete todo #5:
    curl -i -X DELETE http://localhost/todos/5

    Add a new todo
    curl -i -X POST -H ‘Content-Type: application/json’ -d ‘{“task”: “Task x”}’ http://localhost/todos

    Modify todo #6:
    curl -i -X PUT -H ‘Content-Type: application/json’ -d ‘{“task”: “Task 6 updated”}’ http://localhost/todos/6

  • Webtech Mani

    Hi Arjun good tutorial,
    And very much useful beginners

    Thank you

  • Tashneem Jahan

    hi arjun,

    your tutorial is very helpful for me.
    can you help me??
    i go to the below url in browser
    http://localhost/todos/search/bug

    but it gives the error

    Not Found

    The requested URL /todos/search was not found on this server.

  • Raji Philip

    Can you include authentication with it such as api key

  • Kriti Srivasta

    Well DOne and keep it on thanks for this code 🙂 Highly appericiated 🙂 (y)

  • Stenio Barroso

    I was looking for this a long time solved my problem and now I know how to use the slim. Many thanks and a hug.

    Valeu parceiro. rsrsrsrsrs.

  • Sanjiv Kumar

    its code not working on ubuntu 16.04 please help me

    • Are you getting any error?

  • Luca Pighini

    hi arjun,
    Your lesson is really good! ..because not implement image management? It would be really helpful.

    what do you think about it?

    thank you..

    luca

    • Sure will do soon…

  • 김장수

    It’s awesome.
    Thank you very much Arjun!

    How can i wrote log about received parameters from client?

  • Danar

    why add a new todo don’t work ?

    #i’amnewbie

    • Anggi Wijaya

      you must create form for submit data, after creating form you can call the api , with method post to the api

      • Danar

        the api don’t work if you don’t use the postman

        • Can you share error message?

  • Isra Bazan

    your Explanationis really excellent

    • I’m glad you liked it..

  • Ohms238

    Hi at the beginning of my json result I get this character “l”. I’ve checked in the code and i can’t find any thing. There are no other errors. Here is part of the response ” l[{“id”:”4523″,”order_date”:”2017-04-12″… Any ideas?

  • Mohd Amir Gori

    Hi Arjun, do you have any explaination on using these methods in a single “Page Controller” file apart ? I’m having trouble with the issue of not finding the controller class from the index file. Thanks

    • Sorry, Somehow I have missed your comments.. Soon I will right about it

  • Yukon Zhang

    why add a new todo don’t work (on ubuntu 16.04,php 7.0, mysql 5.7)?type: PDOException Code: 23000 Message: SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘task’ cannot be null.

    • you should send “task” via post method, the error indicating that task is not passing to the sql.

      • Yukon Zhang

        thanks a lot, you are right

  • Pingback: Useful Reference For Slim Framework – Beautiful Mind()

  • AH

    man, never delete this post! professors using it for their lecture 😉

    but i have a question, if i had like three tables connected to each other, can i put all the routes in one single .php file or i put every route in a separated .php file?

    • Personally I prefer single route file. Instead of having multiple route files just move your implementations to different files and them import them inside route file.

  • Sourabh Turkar

    very helpful for me thank you Arjun.

    Have you any idea to write multiple routes for users,tasks etc in separate files???

    Thank you
    Sourabh

    • Yes, Tonight I will post about it ….

      • Sourabh Turkar

        thanks

  • Fernando

    Hi, I have an issue in update (PUT) method. The field “task” is always null.

  • Fernando
DMCA.com Protection Status