WebAPI REST Service (MVC Framework)

With the Web API I can easily create a REST service. Theoretically a REST service uses 4 different HTTP verbs to perform the basic CRUD operations on a particular entity. These verbs are:

GET This verb is used to read data
PUT This verb is most often used to update an existing entity
POST This verb is most often used to create a new entity
DELETE This verb is used to delete an entity

In practice what is often done (even why not all browsers support all the methods) is to use the GET verb to read/delete and the POST verb to create/update (we use the POST verb every time we have to send the whole object and not just the id).

Here is an example of a REST service made using a Web API controller:

[RoutePrefix("api/post")]
public class PostController : ApiController
{
    [HttpGet]
    [Route("get")]
    public List<PostModel> Get()
    {
        return new List<PostModel>()
        {
            new PostModel()
            {
                Title = "Post 1",
                Content = "Post 1 Content",
                DateCreated = new DateTime(2015,01,12)
            },
            new PostModel()
            {
                Title = "Post 2",
                Content = "Post 2 Content",
                DateCreated = new DateTime(2015,01,13)
            },
            new PostModel()
            {
                Title = "Post 3",
                Content = "Post 3 Content",
                DateCreated = new DateTime(2015,01,14)
            }
        };
    }
 
    [HttpPost]
    [Route("create")]
    public bool Create([FromBody]PostModel model)
    {
        //Save PostModel to DB
        return true;
    }
}

It can be easily referred by the client using the get()/post() JQuery methods, to invoke the service with the proper HTTP verbs:

<button id="getPost">GET</button>
<button id="createPost">POST</button>

@section scripts
{
    <script>
        $("#getPost").bind("click", function () {
            $.get("/api/post/get", function (data) {
                alert(data);
            });
        });
 
        $("#createPost").bind("click", function () {
            $.post("/api/post/create", {
                title: "Post 4",
                content: "post 4 content",
                dateCreated: "2014/01/16"
            },
            function (data) {
                alert(data);
            });
        });
    </script>
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s