Python示例

星博讯 AI基础认知 1

我来介绍API接口调用的基础知识,让你快速上手:

Python示例-第1张图片-星博讯网络科技知识-SEO优化技巧|AI知识科普|互联网行业干货大全

API 基本概念

API(应用程序编程接口):应用程序之间通信的桥梁,让一个程序可以调用另一个程序的功能。

常见API类型

  • RESTful API:最常用,基于HTTP协议
  • SOAP API:基于XML,较老但更规范
  • GraphQL:可自定义查询内容
  • gRPC:高性能,基于HTTP/2

HTTP 基础方法

GET     /users       # 获取数据
POST    /users       # 创建数据
PUT     /users/1     # 更新整个资源
PATCH   /users/1     # 部分更新
DELETE  /users/1     # 删除数据

API 调用三要素

端点(Endpoint)

https://api.example.com/v1/users
└──────────────┬─────────────┘
     基础URL        资源路径

请求方法

# GET 请求
response = requests.get('https://api.example.com/users')
# POST 请求(发送JSON数据)
data = {'name': 'John', 'age': 30}
response = requests.post('https://api.example.com/users', json=data)

参数传递

查询参数(GET):

GET /users?page=2&limit=20

请求体参数(POST/PUT):

{
  "username": "test",
  "password": "123456"
}

认证方式

# 1. API Key(最简单的认证)
headers = {'X-API-Key': 'your-api-key'}
# 2. Bearer Token(JWT)
headers = {'Authorization': 'Bearer your-token'}
# 3. Basic Auth
auth = ('username', 'password')
response = requests.get(url, auth=auth)
# 4. OAuth 2.0(最复杂但最安全)
headers = {'Authorization': 'Bearer access_token'}

响应处理

import requests
try:
    response = requests.get(
        'https://api.example.com/users',
        headers={'Authorization': 'Bearer token123'},
        params={'page': 1, 'limit': 10},
        timeout=30  # 超时设置
    )
    # 检查状态码
    if response.status_code == 200:
        data = response.json()  # 解析JSON响应
        print(data)
    elif response.status_code == 404:
        print("资源不存在")
    else:
        print(f"错误: {response.status_code}")
except requests.exceptions.Timeout:
    print("请求超时")
except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")

常用状态码

200 OK           # 成功
201 Created      # 创建成功
204 No Content   # 成功但无返回内容
400 Bad Request        # 请求错误
401 Unauthorized       # 未认证
403 Forbidden          # 无权限
404 Not Found          # 资源不存在
500 Internal Server Error  # 服务器错误
502 Bad Gateway            # 网关错误
503 Service Unavailable    # 服务不可用

API 文档关键信息

读文档时关注:

  • 基础URL
  • 认证方式
  • 请求方法
  • 请求参数
  • 响应格式
  • 错误码说明
  • 调用限制(频率限制)

实战示例

调用天气API

import requests
def get_weather(city, api_key):
    url = "http://api.openweathermap.org/data/2.5/weather"
    params = {
        'q': city,
        'appid': api_key,
        'units': 'metric'
    }
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        return f"{city}温度: {data['main']['temp']}°C"
    else:
        return "获取天气失败"

发送文件

# 上传文件
files = {'file': open('report.pdf', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)

分页处理

def fetch_all_users(base_url, token):
    users = []
    page = 1
    while True:
        response = requests.get(
            f"{base_url}/users",
            headers={'Authorization': f'Bearer {token}'},
            params={'page': page, 'per_page': 100}
        )
        if response.status_code != 200:
            break
        page_users = response.json()
        if not page_users:  # 没有更多数据
            break
        users.extend(page_users)
        page += 1
    return users

最佳实践

  1. 错误处理:总添加try-except和状态码检查
  2. 超时设置:避免无限等待
  3. 连接复用:使用Session对象
  4. 日志记录:记录请求和响应
  5. 环境变量:API密钥等敏感信息不要硬编码
  6. 重试机制:对临时失败进行重试
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 创建带重试机制的Session
session = requests.Session()
retry = Retry(total=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

调试工具推荐

  • Postman:API测试和文档
  • cURL:命令行工具
  • 浏览器开发者工具:查看网络请求
  • HTTPie:更友好的命令行工具

这是API调用的基础入门,想了解哪个具体方面的更多细节吗?

标签: 示例

抱歉,评论功能暂时关闭!

微信咨询Xboxun188
QQ:1320815949
在线时间
10:00 ~ 2:00