PHP Restful API Framework SLIM to Create REST API – 1

Hello friends, today we will see how we can use PHP Restful API Framework SLIM to create a REST API for your android application. A REST API is needed to establish the communication between the …

php rest api framework slim to create rest api

Hello friends, today we will see how we can use PHP Restful API Framework SLIM to create a REST API for your android application. A REST API is needed to establish the communication between the app and the server. If we talk about android then we cannot use SQLite only to create our database. We need to create the database in our server. So the communication between our database which is residing in server and our app will be done through REST API.

In this PHP Restful API Framework tutorial we will use SLIM framework to create our REST API.

Update

This post covers the tutorial with SLIM2, but now the framework is updated to SLIM3 and we have some changes. For the updated tutorial you can watch this Play List that covers every detail of building API with SLIM.

Don’t get confused with the title, the First 11 video on this list covers SLIM only, then if you want you can learn implementing the APIs in android as well. 

Prerequisites

To go ahead in this PHP Restful API Framework Tutorial you must have these prerquisites.

  1. Basic Knowledge of PHP
  2. Basic Knowledge of MySQL Queries
  3. PHP Storm IDE (Though you can use any other IDE but I personally love PHP Storm)
  4. WAMP / XAMPP Server (I will be using wamp server)
  5. REST Client for Firefox or Chrome for Testing.

What is REST API?

When a web service use REST Architecture we call it a REST API. REST stands for Representational State Transfer. It relies on a stateless, client-server, cacheable communications protocol, and in virtually all cases, the HTTP protocol is used. REST is an architecture style for designing networked applications.

PHP Restful API Framework SLIM

In this tutorial I will be using SLIM Framework. There are more frameworks available. But I am very comfortable using it. SLIM framework is easy to use and learn. It is also very light weight and supports all kind of requests. So the first thing you need to do is Download SLIM Framework from Here.

What I will be creating in this PHP Restful API Framework Tutorial?

In this tutorial I will create a simple Android App. The app will contain two modules.

1. Student’s Module

The student will login to the app and he/she can see whether his/her assignment is submitted successfully or not. Student can see how many assignment he/she has done so far and what assignment is to be done.

2. Teacher’s Module

Teacher will login to the app and will set an assignment for a particular student. Teacher can change the assignment status to completed if the assignment is completed.

Database Design

For this app the first thing we need is our database. So below you can see the database I have designed.

Database Design
Database Design

You can see our database consist of 3 tables. This is only an abstract model now we need to create the actual database.

Creating Database

  • Go to localhost/phpmyadmin (I am using wamp server, make sure your server is online).
  • Create a new database here (I created db_studentapp).

create database

  • Now click on SQL and run the following batch query.

  • After running the above query you will see your tables are created successfully.

database

  • We have successfully created the database. Keep reading to create the REST API.

Basics of REST API Design

As we have designed our database now we have to create our REST API. Before starting our REST API PHP Project we should know the basics of REST API.

HTTP Methods

A REST API should use the common HTTP methods like GET, POST, PUT, DELETE. These method are used according to the requirement.

GET To Retrieve Values from Database
POST To Insert new Values to Database
PUT To Update Existing Values in the Database
DELETE To Delete Values from Database

HTTP Status Codes

Http Status Codes tells the client about the response. Like if the code is 200 that means the response is ok. The code is 401 then it is an unauthorized request. Below I have mentioned some the the request codes  for a full list of http request codes you can visit this link.

200 OK
201 Created
304 Not Modified
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
422 Unprocessable Entity
500 Internal Server Error

URL Structure

While creating REST API we should create good URLs. The URLs should be understandable and well formed. Every URL must be identified uniquely. For security we use API Key with the request. We should not put the API Key in the URL instead we should put the API Key in the request header. For example you can see the following URLs

URL Method
https://www.simplifiedcoding.net/studentapp/v1/assignments/1 GET

The above URL will give all the assignments of the student having id 1.

URL Method
https://www.simplifiedcoding.net/studentapp/v1/createassignment POST

The above URL will create a new assignment.

API Key

We use an API Key to restrict the access to our API. In this tutorial we will identify each faculty and student with their API Key. As this post is for beginners I am trying to simplify it as much as I can.

Creating Our REST API

Creating PHP Project using PHP Storm

  • I am using PHP Storm as I love this IDE. You can use other IDEs as well. You can also use a normal text editor.
  • First you need to create a PHP Project. I am using wamp server so in my case I should create my project at C:\wamp\www\<Project_folder>.
  • I just created a project at C:\wamp\www\StudentApp. You have to create it in the root directory of your server like it will be htdocs folder in case of xampp and www in case of wamp.

Creating Directories

  • Inside the project you need to create three more folders/directories 1. include, 2. libs, 3. v1.
    In include folder we will keep all the helper classes, in libs folder we will keep all the 3rd party libararies and in v1 folder we will store index.php that will handle all API calls.
    See the snapshot below.

    directory structure
    Directory Structure

Coding Helper Classes

  • Now the first is include. You need to create 3 php files inside include folder. Create Constants.php first and write the following code.

  • Now create DbConnect.php inside include folder. This file will help us to connect with our database. Write the following code inside this file.

  • Now the last file of include folder DbOperation.php, in this file we will write code for all the database related operations. So create DbOperation.php and write the following code.

  • In the above code I have specified methods only for student registration and student login. We have to create all the methods required here like the methods are missing for faculty registration and login. We also need to create the methods to fetch the assignment and update the assignment status. I have not written all the methods here as this tutorial is a bit lengthy I have divided it into two parts. You can find the remaining code in the second part of this PHP REST API Framework SLIM Tutorial.
  • Our helper classes are ready, now we need to handle our API calls.

Handling API Calls

  • Now come inside v1 folder and create file index.php. Here we also need to create .htaccess file to make our URL well formed. So also create .htaccess and write the following rules.

  • Now come inside index.php here we will handle all the individual API calls. Here actuallly our php restful api framework slim will be used.
  • So first create a slim instance and some required methods.

  • The above code consist of the following methods.
    echoResponse() – To display the response in json format.
    authenticateStudent() – To authenticate the student with the api key.
    verifyRequiredParams() – To verify the required parameters in the request.

Student Registration

  • The first task for us is the student registration. So we will create a unique URL for student registration. To do this you need to write the following code inside index.php.

Now we have the following method for student registration in our API.

URL http://localhost/StudentApp/v1/createstudent
Method POST
Parameters name, username, password

The JSON Response 

Student Login

  • After registration the login part comes. So to create login we will again use post method.

Now we have the following method for student registration in our API.

URL http://localhost/StudentApp/v1/studentlogin
Method POST
Parameters username, password

The JSON Response 

Testing Our API

  • To test the API you need a rest client. I am using Rest Easy add on for mozilla firefox. There are many other add ons available you can use any one of them.
  • To test just make a call to the URL using rest client.

rest easy

Conclusion

So I am wrapping up this tutorial here. As this PHP Restful API Framework Tutorial is a bit lengthy. We still need to create many other things in order to make the android application as per the requirement we discussed. So go to the below link to check the next part of this tutorial

PHP Rest API Framework SLIM to Create REST API – 2

And then  after this part of tutorial we will create an Android Application with our RESTful API. If you want to download the source code go to part 2 and you can download the whole source code.

And support us by sharing this PHP Restful API Framework Tutorial among your friends. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.

Expand Your Knowledge: Next Tutorial Picks

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x