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).