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
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:
- Change the return type of your Web API action to
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.
ResponseTypeattribute to the API Method
In addition to
Ok(), there are other methods including
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.
return new StatusCodeResult(HttpStatusCode.Moved, Request);