PHP

PHP RESTful web services

PHP RESTful web services

REST (representational state transfer). We need RESTapi for request and response json datas. The response will be in Json format as well as XM format. PHP frameworks by default have RESTful format to  respond api request. Lets see how to implement Simple RESTful api in php using classes and functions.

My files are :

SimpleRest.php => Which will handle the Http headers and Http status messages.
Db.inc.php => Which will handle the database connection process.
User.php => Which will handle the user table queries.
UserRestHandler.php => Which will handle the User api process.
RestController.php => Which will handle the api routes
.htaccess => Which will handle the api Clean URL’s

Here We have used ‘Advanced Rest Client’ to check API requests locally.

Lets see how it will work:

Let us will connect the database with our application. I have a database called restful and have one table called users.

Db.inc.php

Here we will connect the database with our application.

It will connect our application with database else it will return the error message.

SimpleRest.php

Here we have written the functions to handle the php header functions and http status message.

User.php

Which is going to handle all the users table queries here. Here we have two functions. One is to get all the users table records and another one is to get the user record based in id.

UserRestHandler.php

Which will handle all user request api process and return the result as per user request. The response will be Json, XML or HTML. By default html is a browser view. API will request only json or XML. Here we will get Http request content type and will respond as per.

RestController.php

Here we will map the request URL and will respond as per.

.htaccess

Mobile API will respond only for clean url’s. Here we will write the htaccess to clean the url\

How to Test API Request :

Add ‘Advanced Rest Client’ chrome extension to your browser and open it.

1.Enter your URL :
For example : http://localhost:8888/Marimuthu/vue-php/Rest/users/list/

2. Select method as : GET

3. Under Raw headers Add “Accept: application/json”

4. Click Send button

PHP RESTful Advanced Client

Here you can see your result.

DEMO URLS :

To get all users : http://localhost:8888/Marimuthu/vue-php/Rest/users/list/

To get User by ID : http://localhost:8888/Marimuthu/vue-php/Rest/users/list/1/

Browser URL’s :

http://localhost:8888/Marimuthu/vue-php/Rest/RestController.php?view=all

http://localhost:8888/Marimuthu/vue-php/Rest/RestController.php?view=single&id=1

Hope it will help someone.

Thanks for reading this article if you like this don’t forget to share and comment.