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.

Published by 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.

Join the Conversation

90 Comments

  1. 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.

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

  3. 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.

  4. 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

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

    1. 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’]);

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

  6. 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?

  7. 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

        1. How to Solve Object Not Found Error,Please Help..I kept settings and all as it is in tutorial,but object not found error i am getting

  8. 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.

  9. 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

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

  10. 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?

  11. 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

  12. 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.

  13. 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?

    1. 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.

  14. 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

  15. It’s very useful.
    Could you please tell me the detailed steps to add jwt with this.
    Thanks in advance.

      1. Thanks for your reply, Arjun.
        I have tried it. It showed me the “password credentials do not match our records”. Why do you inserting encrypted password manually? Could you please guide me to resolve this.

  16. Good post, also easy to implement in SLIM3 controller classes.
    I tried it together with axios callse and it worked fine with any passed object
    React with axios calls to SLIM 3 REST API just fit together.

  17. hi arjun,your tutorial is very helpful,but after configuration,i am getting Object Not found error how to solve,Thank you

  18. Hello. I have a question. Can you guide me how can I publish this API built on Slim framework to a linux web hosting? I can’t figure out how to publish it on CPanel.

  19. Hello!! sir through curl data cannot be fetch in form to update data . Could to help to tell how to fetch fetch data and put in form field and then perform update …using curl php

  20. Something i needed to do was place your routes about the route found in the skeleton version of SLIM. I didn’t notice that outlined above and once i figured this out, it worked.

    Thanks!

  21. Hi,
    I had some issues like the host for MySQL, I had to use the IP instead of localhost, and some irrelevant stuff.

    And this tutorial was very helpful, I think you should create the visual part using HTML, TWIG or Pug to call the methods used on this… Because using postman is not enough by now, I guess.

    Cheers,

    Balduino

  22. hi arjun,
    Your lesson is really good! can we implement payment gateway in slim3 ? and how to call external js for stripe checkout It would be really helpful.

    thank you..

Leave a comment

Your email address will not be published. Required fields are marked *