REST

Representational State Transfer

REST is a paradigma for data transfer between client and server. It’s using the verbs GET, POST, PUT, DELETE (and some others) from the HTTP-protokoll,
hence there is almost everywhere a solid infrastructure. For Machine-2-Machine communication REST is a smart choice.

REST deals with resources uniquely identified by URL’s. For Example: http://test.com/restapi/user/5 could be a user ressource with 5 as an user id. By requesting this resource via different types of HTTP verbs typical CRUD (create, read, update, delete) actions can be performed on the ressource.

I will show some very simple ways how to get startet with REST.

Imagine you would call a REST service with curl from the commandline like this (thats a GET request):

curl 'http://test.com/restapi/user/5'

or with a POST request:

curl --data 'firstname=max&lastname=miller' 'http://test.com/restapi/user/5'

The responding server-side could look somewhat like this.
We deal here with pseude-code. Depending on the framework you use, it differs how to access parameters passed alongside the request.

$method = $_SERVER['REQUEST_METHOD'];
        
switch ($method) {
  case 'GET':
    // fetching the user by the id and return it
       break;
  case 'PUT':
    // create a new user and return it
       break;
  case 'POST':
    // alter a user by its id
       break;
  case 'DELETE':
     // delete the user by its id ...
       break;
}

 

CURL

CURL is a mighty tool for transfering data to URLS. It supports a wide range of protocols.

Lets have a closer look on some handy snippets for daily work on the commandline:

Fetching content from a URL

curl http://www.myurl.com

When a page redirects to another location (the respondet http-status is somewhat 3xx)
curl can follow the redirection with the -L (- -location) flag.

curl -L http://www.myurl.com

Want to see what the request and response headers like?
It’s as simple as using the -v (- -verbose) flag.

curl -v http://www.myurl.com

For POSTing data to an URL u can use the parameter -d (- -data) .

curl --data "param1=value1&param2=value2" http://www.myurl.com

You want to upload a file (image.jpg is located in the folder from where you run this command) to a php-script running at localhost/upload.php:

curl -F "data=@image.jpg" localhost/upload.php

a upload-script for taking the uploaded file and store it in a file – the filename is the current timestamp – looks like this:

<?php
if (isset($_FILES)) {
  move_uploaded_file($_FILES['data']['tmp_name'], date('YmdHis'));
}
?>

This is for windows using the cmd. Parsing a folder recursively for all pdf files and send them as a POST request to a certain URI:

for /R %f in (*.pdf) do curl -F "data=@%f" www.mydomain.com/upload