API 简介

Python 中的 API 入门

Chris Ramakers

Engineering Manager

什么是 API?

  • 应用程序编程接口(API)
  • 一组通信规则与能力
  • 使软件应用彼此交互

一个图示:展示邮箱客户端与邮件服务器通过 API 交互,向 john@acme.com 发送邮件。

Python 中的 API 入门

Web API、客户端与服务器

  • Web API 通过互联网使用 HTTP 通信
  • 客户端向服务器发送请求消息
  • 服务器向客户端返回响应消息

一个图示:展示客户端与服务器通过 API 在互联网上交互,并标注请求与响应消息。

  • 请求/响应循环
Python 中的 API 入门

Web API 类型

  • SOAP
    • 侧重严格、规范的 API 设计
    • 企业级应用
  • REST
    • 侧重简单与可扩展性
    • 最常见的 API 架构
  • GraphQL
    • 侧重灵活性
    • 为性能优化
1 https://www.postman.com/state-of-api/api-technologies/#api-technologies
Python 中的 API 入门

在 Python 中使用 API

urllib

  • 随 Python 提供
  • 功能强大但不够友好
from urllib.request import urlopen
api = "http://api.music-catalog.com/"

with urlopen(api) as response:
  data = response.read()
  string = data.decode()
  print(string)

requests

  • 内置功能更强
  • 更易使用
import requests
api = "http://api.music-catalog.com/"

response = requests.get(api)
print(response.text)
Python 中的 API 入门

开始编码!

Python 中的 API 入门

Preparing Video For Download...