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.

125 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

      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.

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

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

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

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

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

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

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

  22. Bedroom furniture sale
    Come in outstanding store in Jefferson Park production for office and home use and cafe! presents over 12000 appointment furniture and goods for a country house and apartments or restaurant. Natural rattan , are used for the purposes of production our branded products , possesses strength and wear resistance, wonderful external data. All furniture processed special compounds, due to which their surface does not absorb water, stable to extremes ambient temperature air and exposure of the sun. Vya our furniture excellent retains its functions even in restaurant in open spaces . In the presented online catalog you offered photos furniture for dining room, hall, bedroom, children’s room , as well as intended for organization of storage area – dressers and cabinets, cabinets and others . In our store in Fairfax you can buy everything for any your home not expensive . We invite client come to store , holding in Westwood what cares about its shopper.

  23. Heya this is somewhat of off topic but I was wanting to know
    if blogs use WYSIWYG editors or if you have to manually code with HTML.

    I’m starting a blog soon but have no coding know-how so I wanted to get guidance from
    someone with experience. Any help would be enormously appreciated!

  24. I all the time used to study piece of writing in news papers but now as I
    am a user of internet so from now I am using net for articles or reviews, thanks to web.

  25. Hello there, I found your web site by the use of Google whilst searching for a similar matter, your site got here up, it appears to be like great.
    I have bookmarked it in my google bookmarks.

    Hi there, simply became aware of your weblog via Google, and
    found that it’s really informative. I’m going to be careful for brussels.
    I will appreciate for those who proceed this in future.
    Lots of folks might be benefited from your writing. Cheers!

  26. We’re a group of volunteers and starting a new scheme in our community. Your site provided us with valuable information to work on. You have done an impressive job and our whole community will be grateful to you.

  27. Right here is the perfect site for everyone who would like to understand this topic. You know so much its almost tough to argue with you (not that I really would want to…HaHa). You certainly put a new spin on a topic which has been discussed for many years. Wonderful stuff, just great!|

  28. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

  29. Its like you read my mind! You seem to know so much about this, like you wrote the book in it
    or something. I think that you could do with
    some pics to drive the message home a bit, but instead of that, this
    is wonderful blog. A fantastic read. I will certainly be back.

  30. You are so interesting! I do not think I’ve truly read through
    something like that before. So good to find someone with some genuine thoughts on this subject matter.
    Seriously.. thank you for starting this up. This site is something that is
    required on the web, someone with some originality!

  31. hey there and thank you for your information – I have
    certainly picked up anything new from right here. I did however expertise some technical issues using this site,
    as I experienced to reload the site many times previous to I could get
    it to load correctly. I had been wondering if
    your web hosting is OK? Not that I’m complaining, but
    sluggish loading instances times will sometimes affect
    your placement in google and can damage your high-quality score if ads and marketing with Adwords.

    Anyway I’m adding this RSS to my e-mail and can look out for a lot more of your respective exciting content.
    Ensure that you update this again soon.

  32. Oh my goodness! Impressive article dude! Thanks, However I am having
    issues with your RSS. I don’t know the reason why I can’t join it.
    Is there anybody having the same RSS problems? Anyone who knows the solution can you kindly respond?
    Thanx!!

  33. I am not sure the place you’re getting your info, however good topic.

    I must spend some time learning much more or working out more.
    Thanks for wonderful info I used to be in search of this information for my
    mission.

Leave a Reply

Your email address will not be published.