PHP Microservices — Creating A Basic Restful Crud API

Devin Dixon
Jan 2 · 4 min read

This tutorial is part of a series of creating Microservices with PHP. Part 1 discussed Sockets, Part 2 discussed RabbitMQ.

One of the most prominent ways to create access to a microservice today is through a RESTful API. REST has great advantages over other protocols like sockets that include:

  1. Non-blocking I/O for the client when implemented in languages like Javascript
  2. Easy to manage resources, meaning its easy to organize and group calls together.
  3. The syntax is easy to follow because it follows HTTP standards
  4. The endpoints are stateless, aka idempotent. This reduces the side effects of unexpected outputs occurring.
  5. Easy to implement CRUD operations — Create, Read, Update, Delete.

Restful over HTTP normally breaks down into 4 types of requests of GET, POST, PUT and DELETE. There are other request types that are outside of the scope of this article. The requests can be described as:

  • GET: Normally maps to an operation of retrieving data. In CRUD, this is your READ.
  • POST: Used for creating data, or in CRUD the CREATE.
  • PUT: Called when a user wants to update data. Is the U in CRUD.
  • DELETE: Used to remove data. And lastly, the DELETE in CRUD.

In this tutorial, we are going to create a small application that executes those 4 methods and represents how we can give access to a microservice. This article will NOT cover areas such as security or access control.

Run The Code

The code for this tutorial is available at: https://github.com/ProdigyView-Toolkit/Microservices-Examples-PHP

Creating The Client

Clients can connect with a Restful through HTTP Requests. These requests can come from multiple sources ranging from Javacript in a browser to a CURL request from a server. In our examples, our request will come from a server.

To start, here is a basic CURL request using ProdigyView’s curl library.

$curl = new Curl($host);
$curl-> send('get');
echo $curl->getResponse();

That will send a GET request to the defined endpoint that the $host variable specifies. If we wanted to add data to our request, we can simply do so by passing an array.

$data = array('id'=>1);
$curl = new Curl($host);
$curl-> send('get', $data);
echo $curl->getResponse();

Very simple. And the POST, PUT and DELETE all work the same. For example, a PUT request.

$curl = new Curl($host);
$curl-> send('put',array('id' => '2', 'title' => 'All About Me'));
echo $curl->getResponse();

And that’s it! This is a relatively simple client for executing the requests. A full example below before we create our server:

The Restful Server

Now we can get into our Restful Microservice. In our service, we are going to imagine this to be a database of articles to manipulate. To be clear, REST is NOT a microservice but gives access to a microservice.

For example, in this tutorial, we are only updating articles. If we wanted, we could create a completely different RESTFUL API to a different service that has its own resources(databases, servers, etc) for modifying information on users but still uses REST and CRUD. Because this new API would only modify users and would have its own resources, it would qualify as a microservice.

Jumping into the code, let us first create mock some data as an example “database”.

Great! Now we need to process the incoming request. That is all handled in ProdigyView’s Request object that processes that current HTTP request and extracts the method and data.

//Create And Process The Current Request
$request = new Request();
//Get The Request Method(GET, POST, PUT, DELETE)
$method = strtolower($request->getRequestMethod());
//RETRIEVE Data From The Request
$data = $request->getRequestData('array');

Next, we need a router. The router will decide how to handle our data depending on the request type (GET, PUT, POST, DELETE).

//Route The Request
if ($method == 'get') {
get($data);
} else if ($method == 'post') {
post($data);
} else if ($method == 'put') {
parse_str($data,$data);
put($data);
} else if ($method == 'delete') {
parse_str($data,$data)
delete($data);
}

Notice in the above for the PUT and DELETE, we use parse_str( $data, $data). This is because PUT and DELETE requests are returned as strings, not as arrays. The string data will be ‘id=1’. We have to turn that data into an array with the parse_str function.

And finally, we write multiple functions for processing the data. As an example, here is the function for processing the GET request.

The function above looks for an ID. If the ID is found it returns that article. If it’s not found, it returns all the articles. The GET in CRUD should only read information without modifying it. And for our response:

echo Response::createResponse(200, json_encode($response));

The Response is ProdigyView’s tool for creating a valid HTTP response. With that, we are JSON encoding our response data to be returned to our client defined above.

Common Misconception: It is sometimes believed that REST has to return JSON. This is not true, REST can return data in any format to the client. For example, we could return the response in XML if we wanted too.

The full example of the server is here:

Wrapping Up And Next Tutorial

To run the above example on your local, you can visit the repo here.

That is the basics for creating a RESTFul CRUD API to connect with a microservice. In production, this will have more features such as security, caching, access control and will likely live inside an MVC. REST APIs can also pipe data to other microservices to accomplish their tasks.

To re-iterate, REST exists both in monolithic applications and microservices. We can use REST and CRUD effectively by separating our operations into different services with their own resources and enabling access to them through via our REST API.

In the next tutorials on PHP and Microservices, we are going to cover:

Helium MVC

The blog of the Helium MVC and ProdigyView Toolkit

Devin Dixon

Written by

Entrepreneur, Technologist, Runner.

Helium MVC

The blog of the Helium MVC and ProdigyView Toolkit

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade