David Corney

Accessing the ONS API

The UK’s Office of National Statistics publishes comprehensive statistics about the economy, population and society at national, regional and local levels. They also have an API, making some of their data available for directly incorporating in other tools and services. This is great: instead of locking data up behind paywalls or limited dashboards, they make it open for others to use as they wish.

Their blog has a very nice essay on how to access data using their API. There’s also their introduction and overview of the api for developers, which includes a few examples in JavaScript.

The ONS is great! We love the ONS! But to be honest, I struggled a bit with their API. Most of the blame lies with me: I don’t use APIs as much as I ought to, and sometimes get my GETS confused with my POSTS. They do provide some documentation but no documentation is ever enough, of course. And I couldn’t find any examples in Python that I could just copy and paste to get going. So I decided to create and share my own examples, to ease the path of anyone following.

I learned how to start with a “dataset” (all the data on a particular topic, like unemployment or GDP), get the correct “version” of that dataset (e.g. the most recent release) from a particular “edition” (all the versions that are compatible: new editions come out when they change what is measured, for example). I then tripped over the notion of “dimensions” for a while.

“Dimensions” refers to particular slices of a dataset. For example, inflation figures might be available for the UK, England, Wales, Scotland and Northern Ireland. So the geography dimension could be set to any one of those areas in order to retrieve all the data relating to one location. I usually want to get a whole time-series for a dataset, so in my code, the “time” dimension is forced to the wildcard “*”. But if you fix the time dimension (e.g. to one year or one month) and set geography to “*”, then it would return the value for every region in turn at the specified time.

And so now there’s my very basic repo on how to access the ONS API via Python. Download it and run the demo script and you’ll see:

  • a list of all available data sets;
  • a list of all the “dimensions” that the UK Labour Market can be analysed along (age groups, seasonally-adjustmented or not, sex, etc.)
  • the actual numbers (“observations”) for a couple of time series.

And that’s it. I might add more flexibility or features later on, but I hope as it stands, someone finds it useful. If so, I’d love to hear from you!