Skip to content

API 入門:從零理解"程序之間的對话"

🎯 核心問题

什么是 API? 這就像問:餐厅的菜單怎么設計,客人一看就懂?服務员怎么記單,不會出錯?API 解决的就是"程序之間如何對话"的問题。你写代碼的第一天就在用 API,只是你可能没意識到。


0. 新手常见的三个困惑

困惑一:API 是很高深的東西吗?

很多人一听到 API,就觉得是高级工程师才能理解的概念。其實你早就用過 API 了:

python
len("hello")        # 這就是 Python 提供的 API
open("file.txt")    # 這也是 API
requests.get(url)   # 這還是 API

困惑二:Web API 和普通 API 有什么區別?

類型調用對象通信方式典型場景
函數 API本地代碼函數調用len(), open()
操作系统 API操作系统系统調用讀写文件、創建進程
Web API遠程服務器HTTP 請求調用 AI 模型、獲取天气

困惑三:我該用 HTTP 還是 SDK?

python
# HTTP 方式:自己處理所有细節
import requests
response = requests.post(
    "https://api.deepseek.com/v1/chat/completions",
    headers={"Authorization": "Bearer sk-xxx"},
    json={"model": "deepseek-chat", "messages": [...]}
)
result = response.json()["choices"][0]["message"]["content"]

# SDK 方式:管家帮你處理
from openai import OpenAI
client = OpenAI(api_key="sk-xxx")
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[...]
)
result = response.choices[0].message.content

1. API 的本质:插頭與插座

API(Application Programming Interface,應用程序編程接口)就是"程序之間對话的约定"。

1.1 用電器來類比

概念電器類比API 對應
接口插座形狀函數簽名 / URL
輸入電流輸入函數參數 / 請求體
輸出電器工作返回值 / 響應體

1.2 三種 API 形態對比

TargetLocal code library
CommunicationFunction call
LatencyNanoseconds
Typical scenariosData processing, file operations
Function API example
len("hello")           # returns 5
max([1, 5, 3])         # returns 5
open("file.txt").read() # reads a file

1.3 函數 API vs HTTP API 的區別

很多初學者會困惑:函數 API 和 HTTP API 到底有什么區別?看文檔時該如何區分?

📚 Function API vs HTTP APILocal calls vs network requests: how should you read the docs?
📦Function API
Call styleDirect function call
ParametersArguments inside parentheses
Return valueReturn value directly
Error handlingException or return value
Python example
# Call a built-in function
length = len("hello")      # returns 5

# Call a library function
import math
result = math.sqrt(16)     # returns 4.0

# Call a custom function
def add(a, b):
    return a + b
sum = add(3, 5)            # returns 8
VS
🌐HTTP API
Call styleNetwork request
ParametersURL / body / headers
Return valueJSON/XML response
Error handlingStatus code checks
HTTP request example
POST /v1/chat/completions HTTP/1.1
Host: api.deepseek.com
Authorization: Bearer sk-xxx
Content-Type: application/json

{
  "model": "deepseek-chat",
  "messages": [
    {"role": "user", "content": "Hello"}
  ]
}
Core point:A function API works locally; an HTTP API communicates remotely. Function docs focus on parameters and return values, while HTTP API docs focus on endpoint, authentication, and request/response formats.

1.4 不同類型的 API 文檔怎么看

面對不同類型的 API 文檔,關注重點各不相同:

📋 How to Read Different Doc TypesFunction docs, REST API docs, and SDK docs each emphasize different things
Doc typeFunction docs
Best forUsing standard library or third-party functions
Difficulty⭐⭐
🔍 What to focus on
Function signatureParameter typesReturn valueExceptionsExample code
📝Doc example
### json.loads(s, *, cls=None, object_hook=None...)

Parse a JSON string into a Python object.

**Parameters:**
- s (str): JSON string to parse
- cls (JSONDecoder): Custom decoder class
- object_hook (callable): Optional conversion function

**Returns:**
- dict | list: Parsed Python object

**Raises:**
- JSONDecodeError: The string is invalid JSON

**Example:**
>>> import json
>>> json.loads('{"name": "Alice"}')
{'name': 'Alice'}
💡Reading tips
  • Read the function signature first to see what parameters are needed.
  • Check parameter types and whether each parameter is required.
  • Check the return type so later code can handle it correctly.
  • Notice possible exceptions and prepare error handling.
📊Quick comparison of three doc types
Item
Function docs
REST API docs
SDK docs
Core focus
Parameters, return values
Endpoint, request body
Initialization, method chain
Code example
Function call
HTTP request
Object method
Error handling
Exceptions/return values
Status codes
Exception objects
Read first
Function signature
Base URL + Auth
Quick Start
Reading advice:For function docs, read the signature. For API docs, read the request format. For SDK docs, read examples first. When stuck, look for Quick Start or Getting Started.

2. 一次完整的 API 調用

👇 動手試試看:點擊下方按钮,观察一次完整的 API 請求-響應流程:

API Request Demo
// Click a command below to simulate API requests
>
💻ClientSends request
Waiting for request...
HTTP Request
🖥️ServerHandles request
Waiting...
HTTP Response
📦ResponseReturns result
Waiting for response...
💡 Click a command button to observe a complete API request-response flow.

2.1 API 調用的四个階段

階段發生了什么電器類比
請求客户端向服務器發送請求按下開關
傳輸請求通過網絡傳輸到服務器電流通過電线
處理服務器處理請求并返回數據電器開始工作
響應客户端接收并處理返回結果灯泡發光

2.2 餐厅類比

餐厅角色API 對應說明
菜單API 文檔告诉你有哪些"菜"可以點
服務员HTTP 協议標準化的"對话方式"
後厨服務端按"订單"處理請求
上菜響應把結果返回给"客人"

3. HTTP 方法:你是在"問"還是在"做"?

調用 Web API 時,你需要告诉服務器你想做什么。這就是 HTTP 方法的由來。

3.1 用餐厅點餐來理解

場景現實中你會怎么說?對應的 HTTP 方法
你想知道今天有什么菜"服務员,菜單给我看看"GET - 纯"問",不改數據
你想點一份宫保鸡丁"给我來份宫保鸡丁"POST - "做"件事,創建數據
你想换一道菜"把宫保鸡丁改成糖醋裡脊"PUT - 替换數據
你想改口味"宫保鸡丁不要放花生"PATCH - 部分修改
你不想要了"算了,那道菜不要了"DELETE - 删除數據
get
Read
Query data
Idempotent
post
Create
Add data
Not idempotent
put
Full update
Replace resource
Idempotent
patch
Partial update
Modify fields
Not idempotent
delete
Delete
Remove resource
Idempotent
getRead - Query data
Fetch resources from the server without changing data
Restaurant analogy:"Waiter, show me the menu"
GET /api/users           # fetch user list
GET /api/users/123       # fetch one user
GET /api/products?cat=phone  # query phone products

關于幂等性

幂等性:多次執行結果是否相同?

  • 幂等的操作(GET/PUT/DELETE):點 10 次和點 1 次,結果一样
  • 不幂等的操作(POST):點 10 次,可能創建 10 个订單

解决方案:POST 操作用唯一 ID 校验,避免重複處理。

3.2 HTTP 方法速查表

方法用途幂等性安全性典型場景
GET獲取资源查询列表、查看詳情
POST創建资源新增用户、提交订單
PUT全量更新替换整个用户资料
PATCH部分更新只修改昵称
DELETE删除资源删除用户、取消订單

4. HTTP 狀態碼:服務器在告诉你什么?

服務器回複時,會先返回一个狀態碼,告诉你請求是否成功。

4.1 狀態碼分類

2xxSuccess
The request was received, understood, and processed successfully
200 OK201 Created204 No Content
3xxRedirect
More action is needed to complete the request
301 Moved Permanently304 Not Modified307 Temporary Redirect
4xxClient error
The request has an error or cannot be completed
400 Bad Request401 Unauthorized403 Forbidden404 Not Found
5xxServer error
The server failed to handle a valid request
500 Internal Error502 Bad Gateway503 Unavailable
💡Memory tip:2️⃣ Success3️⃣ Redirect4️⃣ Client error5️⃣ Server error

4.2 常见狀態碼詳解

狀態碼含義典型場景客户端處理
200 OK成功請求正常處理展示數據
201 Created創建成功POST 請求成功創建资源跳轉到新资源
400 Bad Request請求格式錯误參數缺失或格式不對檢查參數
401 Unauthorized未認證没有提供有效的 API Key引導用户登錄
403 Forbidden无權限API Key 没有访問該资源的權限提示權限不足
404 Not Found不存在請求的地址或资源不存在檢查 URL
429 Too Many Requests請求過多超過了速率限制稍後重試
500 Internal Server Error服務器錯误服務端出了問题提示用户稍後重試

👇 動手試試看:點擊下方按钮,了解常见狀態碼的含義:

HTTP Status Code Demo
// Click a button to inspect status code meanings
>
2xx Success
200OKRequest succeeded
201CreatedResource created
204No ContentSucceeded with no response body
⚠️4xx Client errors
400Bad RequestMalformed request
401UnauthorizedNot authenticated
403ForbiddenNo permission
404Not FoundResource missing
422UnprocessableSemantic validation error
429Too ManyToo many requests
🔴5xx Server errors
500Server ErrorInternal server error
502Bad GatewayGateway error
503UnavailableService unavailable
💡 Click a command button to learn common HTTP status codes.

5. HTTP vs SDK:自己跑腿還是讓管家代辦?

5.1 兩種調用方式對比

🏃 HTTP API🤵 SDK
比喻自己跑腿管家代辦
優點✓ 所有語言都能用
✓ 完全控制請求细節
✓ 无需额外依賴
✓ 代碼简洁易讀
✓ 自動處理鑑權
✓ 內置錯误重試
缺點✗ 需要處理所有细節
✗ 代碼冗長易出錯
✗ 需要安装依賴
✗ 可能有版本問题
代碼示例requests.post(url, json=..., headers={...})client.chat.completions.create(...)

5.2 如何選择?

場景推荐方式原因
快速開發SDK自動處理鑑權、錯误、重試
學習原理HTTP理解底層機制
不支持的語言HTTP任何語言都能用
需要定制HTTP灵活控制每个细節

💡 建议

能用 SDK 就用 SDK,把麻烦事留给庫,把時間留给自己。


6. 如何阅讀 API 文檔?

API 文檔就像說明書和菜單的結合體。你不需要從頭讀到尾,只需要學會"查字典"。

6.1 文檔阅讀清單

打開任何一个 API 文檔(比如 OpenAI 或 DeepSeek),你只需要找這几样東西:

📖API Document Translator
Base URL
https://api.deepseek.com
Endpoint
POST /v1/chat/completions
Headers
Authorization: Bearer sk-xxx
Content-Type: application/json
Body parameters
modelRequiredModel name
messagesRequiredConversation messages
temperatureOptional0-2, default 1
Translate into code
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://api.deepseek.com"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Hello"}]
)
Core idea:When reading docs, find three things: address (Base URL), authentication (Authorization), and parameters.
项目說明示例
Base URLAPI 的根地址https://api.deepseek.com
Authentication如何證明身份Authorization: Bearer sk-xxx
Endpoints具體的接口列表/v1/chat/completions
Parameters必填/可選參數model(必填)、temperature(可選)
Response返回數據結構{"choices": [...]}

6.2 阅讀文檔的步骤

  1. 找到 Base URL - 這是所有請求的前缀
  2. 看懂認證方式 - API Key 放在 Header 還是 Query?
  3. 找到需要的 Endpoint - 你要調用的具體接口
  4. 查看請求參數 - 哪些必填?哪些可選?
  5. 理解返回格式 - 數據是如何組织的?

7. 動手练習:模擬 API 調用

光說不练假把式。這裡有个模擬 API,你可以隨便填參數、隨便改地址,看看會發生什么。

🧪API PlaygroundTry calls without touching a real server
Send a request to see the response
Quick tries:

試着触發以下場景:

  • 成功請求:填入正确的 Endpoint 和 API Key
  • 401 錯误:不填 API Key,看看服務器怎么拒绝你
  • 404 錯误:填一个不存在的地址

8. 小結

核心要點

  1. API 就是傳声筒,帮你把话傳给另一段代碼或遠程服務器
  2. 你早就用過 API 了,從 len()open() 都是 API
  3. Web API 是超能力,讓你調用千裡之外的超级電脑
  4. SDK 是好管家,能用 SDK 就別自己跑腿
  5. 看文檔找三样:地址、鑑權、參數

在 AI 編程的時代,你只需要記住這几个核心概念。剩下的细節,IDE 和 AI 助手會帮你處理。


名词速查表

名词全称解釋
APIApplication Programming Interface應用程序編程接口,定義了軟件之間如何交互
Web API-基于 HTTP 協议的 API,用于網絡通信
Endpoint-端點,API 的具體地址
HTTPHyperText Transfer ProtocolWeb API 使用的通信協议
GET-獲取资源的方法
POST-提交數據的方法
SDKSoftware Development Kit軟件開發工具包,封装了底層 API 調用
URLUniform Resource LocatorAPI 的網絡地址
JSONJavaScript Object Notation常用的數據格式
Authentication-验證身份的過程
Status Code-HTTP 響應中的狀態碼
Request-請求
Response-響應
Header-HTTP 頭,包含元信息
Payload-請求或響應的實际數據
Rate Limit-速率限制
Idempotent-幂等,多次執行結果相同
RESTRepresentational State Transfer一種 API 架構風格
RPCRemote Procedure Call遠程過程調用
GraphQL-一種查询語言 API
gRPC-Google 開發的高性能 RPC 框架