ackerchez
ackerchez

Reputation: 1756

REST http scheme

I am looking to build my first API and I have done a lot of research on the various types of API's out there from SOAP to RESTful API's. I have decided to make use of the RESTful method with http headers as I think it is the method that best serves my needs.

After reading a lot about the way that the RESTful API scheme works I have a question that I was hoping that someone can help me with, this seems like the missing piece of the puzzle to me.

I know that I would typically send data via either POST, GET, PUT, or DELETE to a specific URL something like - app/user/{userid}/{property} but what I don't understand is how that gets interpreted on the server side. Obviously there aren't endless directories for the various users so is this some kind of manipulation in the htaccess file to catch these requests? Can someone shed some light on this matter?

Thanks!

Upvotes: 0

Views: 460

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

Of course there is nothing preventing you from maintaining huge directory structure, creating new files and directories on POST/PUT. But this will be cumbersome and error-prone.

You need some server-side technology. Ideally built with REST in mind. This technology/framework understands URL patterns, is able to map them to controllers/handlers/some piece of code and extract path variables like userid and property in your example.

For example in you have standard that allows you to write:

@Path("app/user/{userid}/{property}")
public class UserResource {

    @GET
    public String getUserProperty(
        @PathParam("userid") int userId, 
        @PathParam("property") String property
    ) {
            //...
    }
}

See how nicely the framework handles low-level stuff? Every time you access e.g. GET app/user/42/salary it will extract 42 and salary for you and call getUserProperty with appropriate arguments.

Another advantage of frameworks like these is automatic marshalling/unmarshalling based on desired Content-type: the library will unmarshall JSON/XML, pass object to your controller methods and marshall returned objects back to some representation.

Upvotes: 2

AdrienBrault
AdrienBrault

Reputation: 7745

You can use a framework to define routes easily.

For example you could use silex in php, with which you could define routes like:

// index.php
require_once __DIR__.'/../vendor/autoload.php'; 

$app = new Silex\Application(); 

// If we stored users in an array ...
$users = array(
    1 => 'Adrien',
    2 => 'John',
);

$app->get('/users/{id}', function($id) use($app, $users) { 
    return $users[$id]; 
}); 

$app->run(); 

You would then be able to curl -X GET -i http://localhost/index.php/users/1

You can look at silex's documentation here http://silex.sensiolabs.org/

Upvotes: 0

Related Questions