in Tutorials

Web services by example 2 of 3

I have built many WebServices APIs over the years. I dealt with multiple server CMS platforms (WordPress, Joomla), in-house servers, PHP, ASP many of which needed some form of RESTful api to communicate with mobile applications.

Here’s the second of a three part tutorial that develops a RESTful web service by example.

This is part 2 of my three part “Web Services by example” -tutorial series. Part 1 can be found here.

Our example

For the purpose of this article, we will develop a “To Do” web service, that will maintain tasks for each user. In RESTful API lingo, the Resource is the task (we will call Tasks), the Collection is the user (we will call Users), as each user will have his own list of tasks.

For simplicity, we will only implement the Task resource APIs, the Users collection will be predetermined. We will have the following data points for the User collection:

User data points
Mike
Maya
Sheila

We will also define our Task resource data model as follows:

Task data model
Property
Task name
Due date
isCompleted

To access Tasks resource, we will use the following HTTP methods in our HTTP requests

CRUD table
CommandHTTP MethodDescription
CreatePOSTCreates a new task
Read (Retrieve)GETFetches list of tasks
Update (Modify)PUTUpdates a specific task
Delete (Destroy)DELETEDeletes a specific task

Finally, we will define the URL endpoint for Tasks resource as:

http://xyz.com/:user/tasks

where :user is a variable that will indicate a collection. In our example its either mike, maya or sheila

Finally, to store the data, we will make a simple database with the following structure:

CREATE TABLE `taskData` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(55) DEFAULT NULL,
  `taskname` text,
  `duedate` TIMESTAMP NULL DEFAULT NULL,
  `completed` INT(1) DEFAULT NULL,
  `completeddate` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Slim Framework

To develop our RESTful api, we will use slim framework.

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Setup

There are many ways to setup Slim on our server, but the simplest and quickest to get you running is to set up with composer. You will need to create a .htaccess file

.htaccess file
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

See here for more details: Route-URL-Rewriting. I recommend that you head on over to Slim framework’s site for installation details, it is easy and simple: Slim framework installation

 

index.php

After setting up Slim, and configuring .htaccess, all the logic for our web service will be inside of index.php file. Slim makes is very easy to setup the routes for our web service.

Here is a simple starting code using Slim in PHP code:

<?php
 
require 'vendor/autoload.php';
$app = new \Slim\Slim();
 
$app->get('/:user/tasks', function ($user) use ($app) {
    $id = $app->request()->get('id');
    if(!is_null($id)) {
        echo "get tasks for $user, with id $id";        
    } else {
        echo "get all tasks for $user";        
    }
});
 
$app->post('/:user/tasks', function ($user) use ($app) {
    $duedate = $app->request()->post('duedate');
    $taskname = $app->request()->post('taskname');
    echo "add new task for $user, name $taskname, due date $duedate";
});
 
$app->put('/:user/tasks', function ($user) use ($app) {
    $id = $app->request()->put('id');
    $duedate = $app->request()->put('duedate');
    $taskname = $app->request()->put('taskname');
 
    echo "update tasks for $user, with id $id, name $taskname, due date $duedate";
});
 
$app->delete('/:user/tasks', function ($user) use ($app) {
    $id = $app->request()->get('id');
    echo "delete tasks for $user, with id $id";
});
 
$app->run();
?>

In the above code, we have built 4 routes: GET, POST, PUT and DELETE as we defined in Part1 of this series.

As a reminder here are the definitions we set out to implement:

HTTP Methods
HTTP MethodDescription
POSTCreates a resource
GETFetches a resource
PUTUpdates a resource
DELETEDeletes a resource

How to test our web service

We have installed Slim framework and wrote our first web service routes and APIs, and that’s great. But how do we test our service?  How do we make sure our APIs are doing what they’re supposed to?

Being a web service has its advantages, its using the most used protocols in our industry. There is no shortage of tools and utilities that can assist us in doing our tests.

One way of testing our web service is by using HTML forms. Although it is not the best choice, and only GET and POST requests can be tested, it can work in a bind.

Another way of testing our web service is by using cURL command line tool. cURL is a tool for getting or sending files and data using the URL syntax. It is the most reliable way to communicate with our web service while in development as it gives us a complete view of the communication over HTTP.

Using cURL

Here is how to make requests with curl  :

curl --request GET 'http://xyz.com/mike/tasks'
curl --request POST 'http://xyz.com/mike/tasks'
curl --request PUT 'http://xyz.com/mike/tasks'
curl --request DELETE 'http://xyz.com/mike/tasks'

To add parameters into each request, use the –data option, data options are URI encoded and URL encoded for special characters (as a regular query string) see example below

curl --request GET 'http://xyz.com/mike/tasks' --data 'id=12'
curl --request POST 'http://xyz.com/mike/tasks' --data 'taskname=Task1&duedate=2014-...'
curl --request PUT 'http://xyz.com/mike/tasks'
curl --request DELETE 'http://xyz.com/mike/tasks'

 


What’s next

At this point, we have built a simple web service for our Tasks resource. I haven’t implemented the logic and database queries in this example as it is beyond the scope of this tutorial. What we’ve learned is how to use Slim framework to do most of the heavy lifting. We have also learned how to test our service using curl command line tool.

Next we will look more into HTTP status codes, considerations when developing a web service and common pitfalls in coding for the web. So stay tuned!

 
UPDATE: Part 3 is now available