Part 1

A quick example of requesting, cleaning up, saving to csv, and then plotting a series from IFS using the API.

Part 2

An example of how to find the dimensions and codes which correspond to your data of interest.

Part 3

How to retrieve the metadata for your series of interest and how to make more advanced requests from the API.

IMF API with Python: An example

The IMF's API allows machine access to macroeconomic data covering more than 180 countries. Using python, it is easy to retrieve data from the API's JSON RESTful Web Service.

The example below retrieves monthly (frequency: M) import price index data (indicator: PMP_IX) for the U.K. (reference area: GB), from the International Financial Statistics (IFS) series. The request returns the base year of the index (the year in which values are indexed to 100), the observation values, and the time period for each value, in this case the year and month. The request is generated by combining the base url of the IMF API, the CompactData method, and the specific code for the series and each dimension of its data. Part 2 covers how to obtain codes and dimension information.


import requests # Python 3.6

url = ''
key = 'CompactData/IFS/M.GB.PMP_IX' # adjust codes here

# Navigate to series in API-returned JSON data
data = (requests.get(f'{url}{key}').json()

print(data['Obs'][-1]) # Print latest observation


	{'@TIME_PERIOD': '2018-03', '@OBS_VALUE': '108.904109589041'}

Pandas to clean the data and save to csv

Next, we'll use pandas to clean up the data obtained above, save it as a csv file, and produce a simple line plot.


import pandas as pd          # pandas version 0.23

baseyr = data['@BASE_YEAR']  # Save the base year

# Create pandas dataframe from the observations
data_list = [[obs.get('@TIME_PERIOD'), obs.get('@OBS_VALUE')]
             for obs in data['Obs']]

df = pd.DataFrame(data_list, columns=['date', 'value'])
df = df.set_index(pd.to_datetime(df['date']))['value'].astype('float')

# Save cleaned dataframe as a csv file
df.to_csv('UK_import_price_index.csv', header=True)

Simple line plot

As the last step for this example, we visually inspect the results by producing a line plot.


# Title and text with recent value
title = f'U.K. Import Prices (index, {baseyr})'
recentdt = df.index[-1].strftime('%B %Y')
recentval = round(df[-1], 1)
recent = f'Most recent: {recentdt}: {recentval}'
source = 'Source: IMF IFS'

# Basic plot
plot = df.plot(title=title, colormap='Set1')
plot = plot.set_xlabel(f'{recent}; {source}')


Pandas Plot Output

Variations: breaking down the request

The IMF's CompactData method, combined with codes for the series, frequency, area, and indicator, returns a JSON structured dataset. The codes and method are explained in more detail as follows:

The order in which codes are combined is referred to as the dimensions of the data, in the IFS case: {Method}/{Series}/{Frequency}.{Area}.{Indicator}.{Date Range}

Part 2 covers how to use the DataStructure method to obtain the dimensions and codes for any series in the API. Part 3 discusses metadata and more complex requests, and also includes some links to additional references.

Next (Part 2) »