Steven Poulton

@CalinLeafshade

5 Small Steps to a Better Web API

Random picture of a Mac, because that’s how work gets done

One of my favourite things to do as a web developer is design and build Single Page Apps. This means that I work very closely with Web APIs on a fairly regular basis. I have even designed Web APIs myself with varying degrees of success.

There are a lot of advantages to building your application in an “API-first” model and it’s certainly becoming more popular so before you embark on your next big build I’d like to share a few small things you can do which will improve the design of your API in a big way.

Before we get started I’d like to mention that these things are still important even if your API is private. Private APIs have a way of becoming public over time as your application develops and besides that, a good API will accelerate the development of your front end clients, whether they are SPAs, mobile apps or scripts.

Use the correct status codes!

The HTTP standard includes a pretty comprehensive array of status codes for servers to return as metadata for the main body. These codes can provide a great way for consumers of your API to figure out what happened programmatically without having to resort to parsing error messages which is brittle.

Status codes come in the following categories:

  • 1xx Informational (mostly for server stuff)
  • 2xx Success!
  • 3xx Redirection
  • 4xx Client error (things the caller can fix)
  • 5xx Server error (things the caller can’t fix)

So I’m sure we’re all familiar with 404 NOT FOUND but what about 409 CONFLICT? Returning these more specific codes helps the client act on errors (or different types of successes) in a more appropriate way.

Oh and for God’s sake, don’t return 200 SUCCESS for everything and rely on a message in the body to explain what happened. It’s obnoxious. Which brings me onto my next point…

Don’t include metadata in the body

When your API returns a response to a request, it will send the majority of the data in the body of the response. That is the purpose of the body. But what if the client has requested a paged view of the data? You need to inform the client of various pieces of metadata like the total number of items in the collection. Where does that go?

A common solution to this problem is to return the data wrapped in some kind of wrapper like so:

{
total: 100,
page: 2,
results: [ ... ]
}

I don’t like this because it blurs the line between the resource and the method by which the resource was received. So where should the metadata go? In the headers.

The HTTP standard allows for custom headers to be sent along with the response. Originally it was recommended that custom headers be prefixed with an X, as in X-Forwarded-By. This recommendation was retracted due to the difficulty in integrating previously non-standard headers into the standard. An alternative to the X prefix, originally designed to avoid conflicts, is to namespace your headers with your application name. For instance:

BobsBurgers-ItemCount: 200

Favour multiple fast requests over monolithic ones

When we consume data from an API instead of a traditional post-back model, we have full control over the UI while the data is loading so we are able to display data to the user in a piecemeal fashion and as soon a the data becomes available. Therefore you should favour a design with multiple, focused endpoints that return quickly rather than a single endpoint per page. The total load time may end up being longer but it doesn’t matter so much if my user can’t see the complicated to calculate rating score for the movie for a few seconds while I give her the synopsis to read. It also allows the client to prioritise requests based on the user’s actions. I might never need to load that rating at all if my user doesn’t scroll down that far.

Generate documentation

Most web frameworks have a best practice for easily generating detailed API documentation. Use it and keep it up to date as part of your build process. It doesn’t need to have a lot of hand-written description but it does need a list of the parameters and an example of a request and a response. Something as simple as this can shave hours off development time in the form of back-and-forth between the API dev and the client dev. Rely on the contract set out in the documentation not on death by a thousand Slack messages.

Be consistent

I should, in theory, be able to accurately guess the URL of the resource I want to access or the action I want to perform given a few examples. It doesn’t really matter what URL scheme you adopt (The REST standard makes no stipulations for instance) as long as you are consistent and predictable. The Principle of Least Astonishment applies here.

If you liked this article please remember to give it some applause to make sure more people get to read it!

Steven Poulton is a web developer and technical architect living in Manchester, England. In his spare time he likes to make indie music, make indie games and play with his indie cats.

More by Steven Poulton

Topics of interest

More Related Stories