Creating REST web application and client with PHP

Nowadays, web services are the ideal way to exchange data between a web application and another web or mobile application. REST, which stands for Representational State Transfer, is a good architectural choice for communication over the internet. It makes sharing data between different devices and apps easier and simpler compared to other methods like SOAP, CORBA, WSDL. REST is not dependent on any protocol, but almost every RESTful service uses HTTP as its underlying protocol.

In this tutorial, I will show you how to:

  • Create a REST web application that connects to a MySQL database to retrieve data.
  • Build a client to communicate with the web service.

REST web application

Let me explain to you how this will work. The client will enter a username, the query will be sent to our web service, the web service will look for that username in the database and then return the user ID, username and email.

Use the following SQL code to create the table users:

Now, open your PHP Editor and let’s get the ball rolling.

This is the configuration I’m using to test the script on a local machine, remember to change these parameters to match your server configuration.

REST web application

The database class (Database.php) will be our web service. It will query the database for the username sent via GET method from the client. Then, it returns the user’s info.

Client Side

The index.php file will be the starting point of our application. It will have an input field where you can enter the username you want to search. Then it will send the text you typed to the web service and get the results. The result is output using var_dump() but you can do a json_decode() which will convert the result into an array to further customize the output.

Use beautiful URLs for your application with Apache server

Everything is working just fine but there is a small tweak we can do to make this even better. We can change the URL from this: https://example.com/rest/database.php?username=johndoe to something like this: https://example.com/rest/database/johndoe

In your .htaccess add the following code:

Please note that rewrite_module should be enabled in your Apache server. If you are using a different web server like ngnix I’m sure there is another way to achieve this.

You can try DHC - REST/HTTP API Client Chrome extension which will help you make direct HTTP/REST resource discovery, manipulation and testing more easily.

This is a very basic example and can be further enhanced. I hope it will help you get started developing web services using REST architecture.