iT邦幫忙

2025 iThome 鐵人賽

DAY 25
0
Software Development

從零開始學 Python系列 第 25

Day 25 – 使用 requests 模組存取 API

  • 分享至 

  • xImage
  •  

今天的學習重點

  • 什麼是 API?
  • requests 模組的基本用法
  • 發送 GET 請求(取得資料)
  • 發送 POST 請求(傳送資料)
  • 簡單範例:查詢即時天氣

一、什麼是 API?

API(Application Programming Interface,應用程式介面)是程式與程式之間的溝通管道。

  • 例如:你要查天氣,不用自己蒐集氣象資料,而是透過氣象局 API 取得 JSON 格式的天氣資訊。
  • 瀏覽器輸入網址會看到網頁;程式透過 API 請求(request)會拿到資料。

二、requests 模組簡介

requests 是 Python 最常用的 HTTP 請求套件,用來與網路服務互動。
安裝:

pip install requests

螢幕擷取畫面 2025-08-27 102037

三、GET 請求

GET 是最常見的請求方式,用來「拿資料」。
範例:抓取一個公開的 API,例如 JSONPlaceholder
(假資料服務):

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)   # 發送 GET 請求

print("狀態碼:", response.status_code)  # 200 代表成功
print("內容:", response.text)           # 純文字
print("JSON:", response.json())        # 自動解析成 dict

輸出:

狀態碼: 200
內容: {"userId": 1, "id": 1, "title": "sunt aut facere...", "body": "..."}
JSON: {'userId': 1, 'id': 1, 'title': 'sunt aut facere...', 'body': '...'}

螢幕擷取畫面 2025-08-27 094121

四、POST 請求

POST 用來「送資料」給伺服器(例如新增一筆資料)。

import requests

url = "https://jsonplaceholder.typicode.com/posts"
data = {"title": "Hello", "body": "This is a test post", "userId": 1}

response = requests.post(url, json=data)

print("狀態碼:", response.status_code)
print("回應 JSON:", response.json())

螢幕擷取畫面 2025-08-27 095041

JSON 資料解析

大多數 API 都回傳 JSON,可以直接用 .json() 轉換為 Python dict。

data = response.json()
print(data["title"])

exercise:查詢即時天氣

這裡示範使用 Open-Meteo API

import requests

url = "https://api.open-meteo.com/v1/forecast"
params = {
    "latitude": 25.0330,   # 台北的緯度
    "longitude": 121.5654, # 台北的經度
    "current_weather": True
}

response = requests.get(url, params=params)

if response.status_code == 200:
    weather = response.json()
    print("台北現在的氣溫:", weather["current_weather"]["temperature"], "°C")
else:
    print("請求失敗,狀態碼:", response.status_code)

螢幕擷取畫面 2025-08-27 095500

學習心得

今天學習了 requests 模組,了解程式如何透過 API 與外部世界連接。GET 請求就像是「去圖書館查資料」,POST 請求就像是「遞交一份表單」。實際操作 API 讓我體會到程式不只是自我運算,還能透過網路獲取龐大的即時資訊!
明天我要學習 BeautifulSoup 套件,嘗試進行「網頁爬蟲初探」,先從簡單的 擷取網頁標題開始!


上一篇
Day 24 – 綜合練習:模組 + OOP + 小系統
下一篇
Day 26 – BeautifulSoup 初探:抓取網頁標題
系列文
從零開始學 Python30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言