云计算、AI、云原生、大数据等一站式技术学习平台

网站首页 > 教程文章 正文

《Python Web API交互》

jxf315 2025-08-03 05:39:22 教程文章 5 ℃

一、Web API基础概念

1. 什么是Web API?

  • 定义:应用程序接口(API)允许不同软件之间通过HTTP协议进行通信。
  • 常见形式:RESTful API(基于JSON/XML)、SOAP、GraphQL。

2. 核心概念

  • HTTP方法:GET(获取)、POST(创建)、PUT(更新)、DELETE(删除)。
  • 状态码:200 OK(成功)、404 Not Found(资源不存在)、401 Unauthorized(认证失败)、500 Internal Server Error(服务器错误)。
  • RESTful架构:资源导向,通过URL定位资源,通过HTTP方法操作资源。

二、Python交互API的核心库

1.requests库(最常用)

import requests

# 发送GET请求
response = requests.get(" https://api.example.com/data ")
print(response.status_code)  # 输出状态码(如200)
print(response.json())       # 解析JSON响应

# 发送POST请求(带JSON数据)
payload = {"key": "value"}
response = requests.post(" https://api.example.com/create ", json=payload)

2.http.client(低级HTTP库)

import http.client

conn = http.client.HTTPSConnection("api.example.com")
conn.request("GET", "/data")
response = conn.getresponse()
print(response.read().decode())
conn.close()

3.aiohttp(异步请求)

import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, " https://api.example.com ")
        print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

三、实战案例:调用第三方API

案例1:获取GitHub用户信息

import requests

def get_github_user(username):
    url = f" https://api.github.com/users/ {username}"
    headers = {"Accept": "application/vnd.github.v3+json"}
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"请求失败:{response.status_code}")

user_data = get_github_user("octocat")
print(f"用户名:{user_data['login']}")

案例2:发送短信(Twilio API)

from twilio.rest import Client

# 配置Twilio账户信息(需替换真实值)
account_sid = "your_account_sid"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)

message = client.messages.create(
    body="自动化运维测试短信",
    from_="+1234567890",  # Twilio分配的号码
    to="+1234567890"      # 接收方号码
)

print(f"短信发送成功,SID:{message.sid}")

四、安全与最佳实践

1. 认证与授权

  • API密钥:通过Header或URL参数传递(如X-API-Key: your_key)。
  • OAuth 2.0:用于第三方授权(如GitHub、Google登录)。
  • Bearer Token:常见于现代API(如JWT)。

2. 数据安全

  • HTTPS:确保通信加密(Python默认启用)。
  • 敏感数据脱敏:避免在日志或错误信息中泄露API密钥。
  • 输入验证:防止恶意输入(如SQL注入)。

3. 错误处理

import requests

try:
    response = requests.get(" https://api.example.com ", timeout=5)
    response.raise_for_status()  # 触发HTTPError异常(如404)
except requests.exceptions.RequestException as e:
    print(f"请求失败:{e}")
except ValueError as e:  # JSON解析错误
    print(f"数据解析失败:{e}")

五、进阶主题

1. 异步请求(高性能场景)

import asyncio
import aiohttp

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        return await asyncio.gather(*tasks)

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.json()

# 并发请求多个URL
loop = asyncio.get_event_loop()
results = loop.run_until_complete(fetch_all([
    " https://api.example.com/data1 ",
    " https://api.example.com/data2 "
]))
print(results)

2. WebSocket通信

import websockets
import asyncio

async def hello():
    uri = "wss://echo.websocket.org"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello, WebSocket!")
        response = await websocket.recv()
        print(f"收到响应:{response}")

asyncio.get_event_loop().run_until_complete(hello())

3. API文档与测试

  • Swagger/OpenAPI:生成交互式API文档(如Swagger UI)。
  • Postman/Insomnia:测试API的工具。
  • 自动化测试:用pytest+requests编写测试用例。

六、总结与下一步

  • 核心收获
  1. 掌握requests库的核心用法。
  2. 了解RESTful API设计原则。
  3. 学会安全调用第三方API。


Tags:

最近发表
标签列表