Vault #9: United Nations (UNHCR) Refugee Data
In this DISCOVERY Data Science Project, you will do real data science in less than an hour and you will earn this project's card to your collection when you fully complete this project! 🎉
Data Source: United Nations High Commissioner for Refugees (UNHCR) Web API
The United Nations High Commissioner for Refugees (UNHCR) is a United Nations agency mandated to aid and protect refugees, forcibly displaced communities, and stateless people, and to assist in their voluntary repatriation, local integration or resettlement to a third country.
The UNHCR has a database of refugees and internally displaced persons (IDPs) around the world. The data is updated daily and includes information on the number of refugees and IDPs, the countries they are from, the countries they are in, and the number of people who have been displaced by conflict or natural disasters.
In addition to being able to access the database via the web, UNHCR also provides a public API that allows you to access the data programmatically. To see the API documentation, click here. In this Project, we'll walk you through accessing this API.
Getting Started: Importing Necessary Libraries
To work with APIs, we need to import the requests library, and we'll also need to import pandas to work with the data. Importing the requests library is done the same way as any standard Python library. For example:
import requests
import pandas as pdWhy requests?
In several previous Projects, you used pd.read_json to access JSON-based APIs. In this Project, we're going to focus on getting raw access to the data -- by using requests library instead of pandas -- and transforming that raw data into a DataFrame and data visualization.
Part 1: Fetching Refugees Data for a Single Year
The UNHCR API allows you to query the data by year, and the first thing we'll need to do is to find what all years are available from the API.
Let's do that!
Part 1.1: Get Available Years
The API documentation includes a GET endpoint that we can use to get a list of all available years of data. The endpoint is:
https://api.unhcr.org/rsq/v1/years
Using the requests library, we can make a GET request to this URL. Type the following code into a new cell in your Jupyter notebook.
response = requests.get("https://api.unhcr.org/rsq/v1/years")
We will also need to convert the response to JSON format. Use the following code to do this.
response.json()
Save the list of years to a list called years.
⚙️ Test Case: Part 1.1: Fetching Refugees Data for a Single Year
Part 1.2: Getting the Number of Refugees for a Single Year
According to the United Nations, 2016 is the year with the most refugees. Let's get the number of refugees for 2016.
The documentation includes a GET request to the /submissions endpoint. The endpoint takes a parameter called year. The request is in the following format, except that {year} must be replaced with the year of interest (in our case, 2016):
https://api.unhcr.org/rsq/v1/submissions?year={year}
Just like in Puzzle #1.1, the GET request will return a JSON object. Fetch the data from the URL above and store the JSON data as refugees_data_2016 using the same command as you did in the previous puzzle:
refugees_data_2016 = response.json()
Extract the Total
In the JSON above, there are many fields. We are interested in the total number of refugees, which is found in the key total. Save just the total key -- by using refugees_data_2016["total"] -- in the variable refugees_2016:
⚙️ Test Case: Puzzle 1.2: Getting the Number of Refugees for a Single Year
Part 2: Fetching Refugees Data for ALL Years
The UNHCR API allows you to query the data for many years.
Part 2.1: Creating a Comma-Separated List of All Years
To reduce the amount of API calls for the years, we can use the year parameter to get the data for multiple years at once. The year parameter can take a list of years.
- To provide a list of years, we need a comma-separated list of years.
- To create a comma-separated list of years, we can use the
joinfunction to join a list of strings together.
Here's how it works:
# Example #1:
myList = ["a", "b", "c"] # Any list.
",".join(myList) # Joins the list elements with a comma between each element.
# Result: "a,b,c"# Example #2:
myList = ["a", "b", "c"] # Any list.
";".join(myList) # Joins the list elements with a semicolon between each element.
# Result: "a;b;c" # Notice the ; instead of the ,# Example #3:
myList = ["Data", "Science", "DISCOVERY"]
";".join(myList)
# Result: "Data;Science;DISCOVERY"Lists of Integers
Our data is slightly more complex, since we have years as integers (ex: [2003, 2004, ...]). The only additional change we need to make is to convert the list to a string as part of joining the elements together by using the map function inside of our join function:
# Example #4:
myList = [20, 30, 40] # List of integers
",".join(map(str, myList)) # Note the use of the `map(str, ...)` inside of join
# Result: "20,30,40" # to convert the integers into strings# Example #5:
myList = [2003, 2004, 2005, 2006] # List of integers
"+".join(map(str, myList)) # Map the integers to strings, then join them
# Result: "2003+2004+2005+2006" # with a "+" between each oneCreating Our Comma-Separated List of Years
In Puzzle 1.1, you created a years variable, let's refresh our memory on what's in it by running the cell below:
Using all that you know now, create a comma-separated list of all years in a variable called years_csv:
Part 2.2: URL Encoding Multiple Years
Finally, to send a list in a URL, the list needs to be formatted as a URL with "URL Encoding".
- Your
years_csvis a comma-separated string:"2003,2004,2005,2006[...]" - However, URL encoding requires some characters to be "escaped" and would be written as:
"2003%2C2004%2C2005%2C2006[...]- The "escape character" in URL strings is
%and it must be followed with a two-letter code to represent the escaped character as another character. - For example,
?will be encoded as%3F(3Fis hexadecimal for the number63, and63is the ASCII code for?) - Similarly,
,will be encoded as%2C(2Cis hexadecimal for the number44, and44is the ASCII code for,) - Since
%is the escape character, it must be escaped itself! (%is encoded as%25.)
- The "escape character" in URL strings is
Python provides the urllib library and the urllib.parse.quote function to do URL encoding. See the following examples of using urllib.parse.quote:
import urllib
urllib.parse.quote("?%,") # All characters need encoding
# Result: %3F%25%2Curllib.parse.quote("2016,2017") # Only the comma needs encoding
# Result: 2016%2C2017myString = "Hello, world! %)" # Storing a string in a Python variable
urllib.parse.quote(myString) # ...and then encoding the contents of that variable.
# Result: Hello%2C%20world%21%20%25%29Use the urllib.parse.quote function to encode the variable years_csv that you created in the previous code cell. Save this encoded string as a new variable encoded_years:
⚙️ Test Case: Part 2.1 and 2.2: Fetching Refugees Data
Part 2.3: Fetching the Number of Refugees for All Years
In Part 1.2, you found the number of refugees in 2016. Let's get the number of refugees for ALL years!
- Identical to Part 1.2, create a
refugees_data_ALLvariable that contains the refugee data from the API for ALL years.
You will still use the same endpoint:
https://api.unhcr.org/rsq/v1/submissions?year={year}
However, {year} should now use your encoded_years with all years INSTEAD OF just a single year. Store the response JSON as the variable refugees_data_ALL:
Create a DataFrame
In the JSON above, there are many fields. We are interested in the total number of refugees each year, all of which is found in the key results. Since it is already a list of dictionaries, it can automatically be used as a DataFrame.
Using pd.DataFrame(...), create a new DataFrame refugees_per_year from the refugees_data_ALL["results"] data:
⚙️ Test Case: Puzzle 2.3: Fetching the Number of Refugees for All Years
Part 3: Creating a Bar Chart of Refugees by Year
Finally, let's create a bar chart! Since we imported the DataFrame from a JSON object, all of the data in the DataFrame are generic "objects" (even though they're numbers). You can see the type of data being stored in each column by running refugees_per_year.dtypes:
To convert data to the best numeric format, the pd.to_numeric transforms a column into a numeric data type. To convert the "year" column from a generic object:
refugees_per_year['year'] = pd.to_numeric(refugees_per_year['year'])Convert both year and persons column into numeric columns:
Let's check out how the data types (dtypes) have changed:
Finally, let's check out our plot:
⚙️ Test Case: Part 3: Creating a Bar Chart of Refugees by Year
Validate and Complete This Project!
Congratulations on finishing this DISCOVERY Data Science Project! 🎉🎉
To validate your entire project, your entire code will run from top-to-bottom on this page and each test case will be validated one final time. If everything looks good, you'll earn the card for completing this project: