Swagger(现在通常称为OpenAPI)是一种流行的API描述格式,在Linux环境下有几种测试Swagger API的方法:
# 克隆Swagger UI仓库
git clone https://github.com/swagger-api/swagger-ui.git
# 进入目录
cd swagger-ui
# 安装依赖
npm install
# 运行Swagger UI (需要Node.js)
npm start
然后访问 http://localhost:3200
并输入你的Swagger/OpenAPI规范URL。
# GET请求示例
curl -X GET "http://api.example.com/users" -H "accept: application/json"
# POST请求示例
curl -X POST "http://api.example.com/users" \
-H "accept: application/json" \
-H "Content-Type: application/json" \
-d '{"username":"testuser","email":"test@example.com"}'
# 安装HTTPie
sudo apt install httpie # Ubuntu/Debian
sudo dnf install httpie # Fedora
sudo pacman -S httpie # Arch Linux
# 使用示例
http GET http://api.example.com/users
http POST http://api.example.com/users username=testuser email=test@example.com
Postman也提供了Linux版本:
另一个流行的API测试工具:
# Ubuntu/Debian
sudo snap install insomnia
# 或者使用AppImage
wget https://github.com/Kong/insomnia/releases/download/core%402021.5.0/Insomnia.Core-2021.5.0.AppImage
chmod +x Insomnia.Core-2021.5.0.AppImage
./Insomnia.Core-2021.5.0.AppImage
# 下载Swagger Codegen
wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.25/swagger-codegen-cli-3.0.25.jar -O swagger-codegen-cli.jar
# 生成客户端代码
java -jar swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l python \
-o /tmp/python-client
# 拉取Swagger UI镜像
docker pull swaggerapi/swagger-ui
# 运行容器
docker run -p 8080:8080 -e SWAGGER_JSON=/foo/swagger.json -v /path/to/your/swagger.json:/foo/swagger.json swaggerapi/swagger-ui
然后访问 http://localhost:8080
import requests
response = requests.get('http://api.example.com/users')
print(response.json())
-v
或 --verbose
选项可以获得更详细的调试信息选择哪种方法取决于你的具体需求和偏好,命令行工具适合快速测试和自动化,而图形界面工具如Postman或Swagger UI则提供更直观的交互体验。