Tuesday, September 25, 2012

Simple Web API

The few last months I have been playing around a lot with NodeJS. That has caused me to play with simple Rest API calls.  It's quite neat, you are basically able to do whatever you want with Javascript.  And using JSON you can quite easily communicate with your server.

I've recently installed Visual Studio 2012 ( thought I'd have a play with it), and I immediately wanted to play with the WebAPI.  It had already intrigued me when I had seen a talk by Glen Block about it at tech days.  Although, back then it was still unfinished.  So I was keen to see what it was doing now.  Since I had not played with MVC4, it's basically an intro for me.

When creating a new empty MVC4 project, the wizard will create a project structure.  Most notably for this spike it contains a "App_Start" and a "Controllers" folder.

The "App_Star" folder will contain a class called  WebApiConfig which has already some default routing setup to "/api/{controllerName}".

We can map a controller to this route by adding a new controller inheriting from the ApiController class in the "Controllers" folder.

public class NoteController : ApiController
    {
        public IEnumerable<Note> Get()
        {
            return new Note[] 
            { 
                new Note 
                {
                    Title = "ABC", 
                    Desciption = "value2" 
                } 
            };
        }
    }

The "Get" method basically maps to the Http GET method, it will do the same for POST, PUT, DELETE,...

What's cool is that it will serialize the DTO and output xml or json depending on the accept headers of the request.

If you want to force the output to be of another format you can  configure a querystring to output the correct result when calling the api.


GlobalConfiguration.Configuration
                .Formatters
                .JsonFormatter
                .MediaTypeMappings
                .Add(new QueryStringMapping("json", "true", "application/json"));

Calling "localhost/api/note?json=true" will then return : "[{"Title":"ABC","Desciption":"value2"}]"

To be fair, this does feel like a bulky way to do this, so if anyone knows of a better way, i'd be interested to know.

No comments:

Post a Comment