API 接口调用 - 第三方服务集成

API 接口调用教程,学会连接第三方服务

预计阅读时间:3 分钟

API 接口调用 - 第三方服务集成

学会 API 调用,就能连接整个互联网!


目录

  1. 什么是 API?
  2. API 基础概念
  3. 调用流程
  4. 实战案例
  5. 认证方式
  6. 常见错误处理

1. 什么是 API?

API = Application Programming Interface

简单说:软件之间沟通的桥梁

你的程序 ←API→ 微信/支付宝/地图...

2. API 基础概念

常见 API 类型

类型 说明 示例
REST 最常用 URL + JSON
GraphQL 灵活查询 单端点
WebSocket 实时通信 双向通信

HTTP 方法

方法 说明
GET 获取数据
POST 提交数据
PUT 更新数据
DELETE 删除数据

3. 调用流程

1. 阅读文档
2. 获取 API Key
3. 发送请求
4. 解析响应
5. 错误处理

4. 实战案例

案例一:天气查询

import requests

def get_weather(city="北京"):
    url = f"https://api.example.com/weather"
    params = {
        'city': city,
        'key': 'YOUR_API_KEY'
    }

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

    return data['weather'], data['temperature']

# 使用
weather, temp = get_weather("上海")
print(f"上海天气:{weather},温度:{temp}°C")

案例二:发送邮件

import smtplib
from email.mime.text import MIMEText

def send_email(to, subject, body):
    # 配置
    smtp_server = 'smtp.gmail.com'
    smtp_port = 587
    sender = 'your@gmail.com'
    password = 'your_app_password'

    # 构建邮件
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['Subject'] = subject
    msg['To'] = to

    # 发送
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, [to], msg.as_string())

    print("邮件发送成功!")

# 使用
send_email('to@example.com', '测试', '这是一封测试邮件')

5. 认证方式

方式 说明
API Key 简单密钥
OAuth 授权登录
JWT Token 认证
Bearer Token HTTP 认证

示例:Bearer Token

headers = {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Content-Type': 'application/json'
}

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

6. 常见错误处理

import requests

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()  # 检查 HTTP 错误

    data = response.json()
    print(data)

except requests.exceptions.Timeout:
    print("请求超时")
except requests.exceptions.ConnectionError:
    print("网络连接错误")
except requests.exceptions.HTTPError as e:
    print(f"HTTP错误: {e}")
except Exception as e:
    print(f"其他错误: {e}")

常用 API 推荐

服务 API 用途
天气 OpenWeatherMap 天气查询
地图 高德/百度/腾讯 地图服务
短信 阿里云/腾讯云 验证码
支付 支付宝/微信 支付接口
AI OpenAI/DeepSeek 智能对话

标签: #Python #API #接口


本文由 suisui 发布