ASP.NET Web API - Screencast series Part 3: Delete and Update

We're continuing a six part series on ASP.NET Web API that accompanies the getting started screencast series. This is an introductory screencast series that walks through from File / New Project to some more advanced scenarios like Custom Validation and Authorization. The screencast videos are all short (3-5 minutes) and the sample code for the series is both available for download and browsable online. I did the screencasts, but the samples were written by the ASP.NET Web API team.

In Part 1 we looked at what ASP.NET Web API is, why you'd care, did the File / New Project thing, and did some basic HTTP testing using browser F12 developer tools.

In Part 2 we started to build up a sample that returns data from a repository in JSON format via GET methods.

In Part 3, we'll start to modify data on the server using DELETE and POST methods.

[Video and code on the ASP.NET site]

So far we've been looking at GET requests, and the difference between standard browsing in a web browser and navigating an HTTP API isn't quite as clear. Delete is where the difference becomes more obvious. With a "traditional" web page, to delete something'd probably have a form that POSTs a request back to a controller that needs to know that it's really supposed to be deleting something even though POST was really designed to create things, so it does the work and then returns some HTML back to the client that says whether or not the delete succeeded. There's a good amount of plumbing involved in communicating between client and server.

That gets a lot easier when we just work with the standard HTTP DELETE verb. Here's how the server side code works:

public Comment DeleteComment(int id)  
{ 
    Comment comment; 
    if (!repository.TryGet(id, out comment)) 
        throw new HttpResponseException(HttpStatusCode.NotFound); 
    repository.Delete(id); 
    return comment; 
} 

If you look back at the GET /api/comments code in Part 2, you'll see that they start the exact same because the use cases are kind of similar - we're looking up an item by id and either displaying it or deleting it. So the only difference is that this method deletes the comment once it finds it. We don't need to do anything special to handle cases where the id isn't found, as the same HTTP 404 handling works fine here, too.

Pretty much all "traditional" browsing uses just two HTTP verbs: GET and POST, so you might not be all that used to DELETE requests and think they're hard. Not so! Here's the jQuery method that calls the /api/comments with the DELETE verb:

$(function() { 
    $("a.delete").live('click', function () { 
        var id = $(this).data('comment-id'); 
 
        $.ajax({ 
            url: "/api/comments/" + id, 
            type: 'DELETE', 
            cache: false, 
            statusCode: { 
                200: function(data) { 
                    viewModel.comments.remove( 
                        function(comment) {  
                            return comment.ID == data.ID;  
                        } 
                    ); 
                } 
            } 
        }); 
 
        return false; 
    }); 
});

So in order to use the DELETE verb instead of GET, we're just using $.ajax() and setting the type to DELETE. Not hard.

But what's that statusCode business? Well, an HTTP status code of 200 is an OK response. Unless our Web API method sets another status (such as by throwing the Not Found exception we saw earlier), the default response status code is HTTP 200 - OK. That makes the jQuery code pretty simple - it calls the Delete action, and if it gets back an HTTP 200, the server-side delete was successful so the comment can be deleted.

Adding a new comment uses the POST verb. It starts out looking like an MVC controller action, using model binding to get the new comment from JSON data into a c# model object to add to repository, but there are some interesting differences.

public HttpResponseMessage<Comment> PostComment(Comment comment)  
{ 
    comment = repository.Add(comment); 
    var response = new HttpResponseMessage<Comment>(comment, HttpStatusCode.Created); 
    response.Headers.Location = new Uri(Request.RequestUri, "/api/comments/" + comment.ID.ToString()); 
    return response; 
} 

First off, the POST method is returning an HttpResponseMessage<Comment>. In the GET methods earlier, we were just returning a JSON payload with an HTTP 200 OK, so we could just return the  model object and Web API would wrap it up in an HttpResponseMessage with that HTTP 200 for us (much as ASP.NET MVC controller actions can return strings, and they'll be automatically wrapped in a ContentResult). When we're creating a new comment, though, we want to follow standard REST practices and return the URL that points to the newly created comment in the Location header, and we can do that by explicitly creating that HttpResposeMessage and then setting the header information.

And here's a key point - by using HTTP standard status codes and headers, our response payload doesn't need to explain any context - the client can see from the status code that the POST succeeded, the location header tells it where to get it, and all it needs in the JSON payload is the actual content.

Note: This is a simplified sample. Among other things, you'll need to consider security and authorization in your Web API's, and especially in methods that allow creating or deleting data. We'll look at authorization in Part 6. As for security, you'll want to consider things like mass assignment if binding directly to model objects, etc.

In Part 4, we'll extend on our simple querying methods form Part 2, adding in support for paging and querying.

1 Comment

Comments have been disabled for this content.