Web API Deep Dive – HTTP Response Codes (Part 2 of 6)

Microsoft’s ASP.Net Web API 2.2 allows you to easily create REST style APIs on an IIS website. Microsoft has some great documentation on how to get started with it, so I won’t rehash that here. Instead, I’m going to go a little deeper into some powerful features that can be used with Web API.

Part 1 - Customizing auto-generated documentation
Part 2 - HTTP Response Codes (this article)
Part 3 - HTTP Error Codes from Exceptions
Part 4 - OData URL Query Options
Part 5 - DTO Transformations and Automapper
Part 6 - Testing with EF Rollbacks across HTTP

Using Appropriate HTTP Response Codes

When building an HTTP REST API, you should use appropriate HTTP response codes to indicate the status of a response. This uses the semantics of HTTP to communicate the status rather than inventing something new. Here are the three response codes I use most often:

HTTP 200 - Everything is OK
HTTP 201 - Something was created
HTTP 404 - Something could not be found

I only explicitly do this for methods that return a single object. For Web API methods that return a collection, I don’t worry about what’s written in this blog post. That’s because if I successfully return a collection, Web API will by default return HTTP 200 OK. If it can’t find any items, I return an empty collection, which still by default returns HTTP 200 OK. And if there is an error, the error handling filter returns the appropriate HTTP Status code for the error (more details on this in next week’s post).

To return the appropriate HTTP response codes, there are 3 steps:

  1. Change the return type of your Web API action to IHttpActionResult.
  2. Wrap your return value in one of the helper methods, such as Ok()

    After following these steps, you might notice that the auto-generated documentation (see part 1 of this series) can no longer figure out the type of the data being returned by your API method. Thankfully, there is a helpful attribute to give the documentation generator a hint: ResponseType. Add this attribute to your method and your Documentation should pick up the response type for the method. Note that you can include this attribute multiple times with different types listed, which can be helpful if a single API method has several possible return types.

  3. Add ResponseType attribute to the API Method

1
2
3
4
5
6
7
8
9
[ResponseType(typeof(Order))]
public IHttpActionResult GetOrder(int orderId)
{

var order = orderFinder.FindOrder(orderId);
if (order == null)
return NotFoundResult(Request);
else
return Ok(order);

}

In addition to Ok(), there are other methods including BadRequest(), NotFoundResult(), Created(), and more. If you can’t find the HTTP Status code that you want to use, you can use the generic one, which allows you to use any of the 48 codes in the System.Net.HttpStatusCode enum.

1
return new StatusCodeResult(HttpStatusCode.Moved, Request);