Main Content

Download Data from Web Service

This example shows how to download data from a web service with the webread function. The World Bank provides various climate data via the World Bank Climate Data API. A call to this API returns data in JSON format. webread converts JSON objects to structures that are convenient for analysis in MATLAB®.

Use webread to read USA average annual temperatures into a structure array.

api = '';
url = [api 'country/cru/tas/year/USA'];
S = webread(url)
S = 

112x1 struct array with fields:


webread converted the data to a structure array with 112 elements. Each structure contains the temperature for a given year, from 1901 to 2012.

ans = 

    year: 1901
    data: 6.6187
ans = 

    year: 2012
    data: 7.9395

Plot the average temperature per year. Convert the temperatures and years to numeric arrays. Convert the years to a datetime object for ease of plotting, and convert the temperatures to degrees Fahrenheit.

temps = [];
temps = 9/5 * temps + 32;
years = [S.year];
yearstoplot = datetime(years,1,1);
plot(yearstoplot, temps);
title('USA Average Temperature 1901-2012')
ylabel('Temperature (^{\circ}F)')
xmin = datetime(1899,1,1);
xmax = datetime(2014,1,1);
xlim([xmin xmax])

USA average temperature plotted as temperature in degrees Fahrenheit by year

Overplot a least-squares fit of a line to the temperatures.

p = polyfit(years,temps,1);
ptemps = polyval(p,years);
deltat = p(1);
hold on
fl = plot(yearstoplot, ptemps);
xlim([xmin xmax])
title('USA Average Temperature Trend 1901-2012')
ylabel('Temperature (^{\circ}F)')
deltat = num2str(10.0*deltat);
legend(fl,['Least Squares Fit, ', deltat, '^{\circ}F/decade'])
hold off

USA average temperature trend plotted as temperature in degrees Fahrenheit by year

API and data courtesy of the World Bank: Climate Data API. (See World Bank: Climate Data API for more information about the API, and World Bank: Terms of Use.)