API已成为数字经济的核心,本文分析REST、GraphQL、gRPC的技术对比和API网关选型趋势。
API市场规模
| 指标 |
数据 |
| API经济规模 |
5万亿美元 |
| API调用增长 |
年增30% |
| 开发者数量 |
3000万+ |
| API产品数量 |
5000万+ |
REST vs GraphQL vs gRPC
对比概览
| 特性 |
REST |
GraphQL |
gRPC |
| 数据格式 |
JSON |
JSON |
Protobuf |
| 学习成本 |
低 |
中 |
高 |
| 性能 |
中 |
中 |
高 |
| 灵活性 |
低 |
高 |
高 |
| 缓存 |
简单 |
复杂 |
复杂 |
| 适用场景 |
通用 |
移动端 |
微服务 |
REST API设计
### 获取文章列表
GET /api/v1/articles?page=1&limit=10
### 获取单篇文章
GET /api/v1/articles/{id}
### 创建文章
POST /api/v1/articles
Content-Type: application/json
{
"title": "文章标题",
"content": "文章内容"
}
GraphQL API
query GetArticle($id: ID!) {
article(id: $id) {
id
title
content
author {
name
avatar
}
comments {
content
createdAt
}
}
}
mutation CreateArticle($input: ArticleInput!) {
createArticle(input: $input) {
id
title
}
}
gRPC服务
// article.proto
syntax = "proto3";
service ArticleService {
rpc GetArticle (ArticleRequest) returns (Article);
rpc ListArticles (ListRequest) returns (ArticleList);
}
message Article {
int64 id = 1;
string title = 2;
string content = 3;
}
// Go实现
func (s *server) GetArticle(ctx context.Context, req *pb.ArticleRequest) (*pb.Article, error) {
return &pb.Article{
Id: req.Id,
Title: "Example",
}, nil
}
API网关选型
开源方案
| 网关 |
特点 |
性能 |
| Kong |
功能丰富 |
高 |
| Apache APISIX |
云原生 |
高 |
| Tyk |
轻量 |
中 |
| Gloo |
插件化 |
高 |
Kong配置示例
services:
kong:
image: kong:latest
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: postgres
KONG_DECLARATIVE_CONFIG: kong.yml
ports:
- "8000:8000"
services:
- name: article-service
url: http://article-service:8080
routes:
- name: articles
paths:
- /api/articles
plugins:
- name: rate-limiting
config:
minute: 60
policy: redis
API认证方案
JWT认证
// 签发Token
const token = jwt.sign(
{ userId: 123, role: 'admin' },
SECRET_KEY,
{ expiresIn: '7d' }
);
// 验证Token
const decoded = jwt.verify(token, SECRET_KEY);
OAuth 2.0
// 授权码流程
const authUrl = 'https://auth.example.com/authorize';
const params = new URLSearchParams({
client_id: 'YOUR_CLIENT_ID',
redirect_uri: 'https://your-app.com/callback',
response_type: 'code',
scope: 'read write',
});
API安全最佳实践
| 实践 |
说明 |
| HTTPS |
所有通信加密 |
| 限流 |
防止滥用 |
| 输入验证 |
过滤恶意数据 |
| 鉴权 |
JWT/OAuth |
| 审计日志 |
记录操作 |
| CORS |
控制跨域 |
2026年新趋势
- GraphQL Federation:微服务统一入口
- API-first:先设计API后开发
- AI API:AI能力产品化
- Event-driven:事件驱动架构
- API合约:OpenAPI 3.1普及
工具推荐
| 工具 |
用途 |
| Postman |
API调试 |
| Insomnia |
API客户端 |
| Swagger |
API文档 |
| Stoplight |
API设计 |
API经济正在重塑商业和技术格局,选择合适的技术栈是API战略成功的关键。
评论(0)