開始使用免費開始

基本 API 請求

在這個練習中,你要組出一個 API 請求,擷取美國各州的平均家庭人數與年齡中位數。資料來自 2010 年十年人口與住宅普查的 Summary File 1。

已為你匯入 requests

本練習屬於課程

使用 Python 分析美國 Census 資料

檢視課程

練習說明

  • yeardataset 指定合適的字串值,以從十年人口與住宅普查的 Summary File 1 取得 2010 年的資料。
  • 建立 get_vars(要請求的普查變數清單),其變數名稱為:"NAME""P013001"(年齡中位數)、"P037001"(平均家庭人數)。
  • 使用 print 函式輸出 r.text

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Build base URL
HOST = "https://api.census.gov/data"
year = ____
dataset = ____
base_url = "/".join([HOST, year, dataset])

# Specify Census variables and other predicates
get_vars = ____
predicates = {}
predicates["get"] = ",".join(get_vars)
predicates["for"] = "state:*"

# Execute the request, examine text of response object
r = requests.get(base_url, params=predicates)
print(____)
編輯並執行程式碼