Files
2026-10-20 21:19:44 +08:00

100 lines
3.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 2.6 第一个接口调试
:::tip 概述
本节通过三个最基础的接口(健康检查 → 登录 → 带令牌调用业务接口)带你完成第一次接口调试。项目内置 OpenAPI 文档(/api.json)与本地 Redoc 页面(/swagger),可在线查看全部接口并调试。
:::
## 接口调试三步走
### 第一步:健康检查(免登录)
```sh
curl http://127.0.0.1:8000/api/health
```
```json
{"code":0,"ok":true,"msg":"操作成功","data":{"status":"up"}}
```
### 第二步:获取验证码 + 登录
```sh
# 1. 获取图形验证码(公开接口)
curl http://127.0.0.1:8000/api/captcha
# 返回 {"key":"uuid...","captcha":"data:image/png;base64,..."}
# 2. 登录(公开接口;开发环境可携带万能验证码 bypassCode 免校验)
curl -X POST http://127.0.0.1:8000/api/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"123456","code":"618618","key":"上一步返回的key"}'
```
登录成功返回(**OAuth2 惯例下划线命名**):
```json
{
"code": 0, "ok": true, "msg": "操作成功",
"data": {
"access_token": "eyJhbGciOiJIUzI1NiIs…",
"refresh_token": "eyJhbGciOiJIUzI1NiIs…",
"expires_in": 7200,
"token_type": "Bearer"
}
}
```
### 第三步:带令牌调用业务接口
```sh
curl http://127.0.0.1:8000/api/user/page?pageNo=1&pageSize=3 \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs…"
```
分页响应(统一信封 + PageData):
```json
{
"code": 0, "ok": true, "msg": "操作成功",
"data": {
"records": [ { "id": 1, "username": "admin", … } ],
"total": 1, "size": 3, "current": 1, "pages": 1
}
}
```
## 在线文档调试
浏览器打开:
| 地址 | 内容 |
|------|------|
| `http://127.0.0.1:8000/swagger` | 本地托管 Redoc UI(免登录) |
| `http://127.0.0.1:8000/api.json` | 原生 OpenAPI JSON(gmeta 补注册生成) |
gmeta 注解(method/path/summary/permission)会完整体现在文档中,接口与文档天然同步。
## 响应信封约定
| 字段 | 说明 |
|------|------|
| `code` | 0=成功;1=通用失败;401=未认证(HTTP 401);403=无权限;429=限流;其余业务码见 [8.2 错误码对照表](../api-spec/error-code) |
| `ok` | 布尔,与 code==0 等价 |
| `msg` | 提示信息,失败时前端弹出 |
| `data` | 业务数据,失败时为空对象 `{}` |
## 认证方式速记
```text
1. access_token 放 Header:Authorization: Bearer <token>
2. access_token 过期(401)→ POST /api/oauth2/token
{"grant_type":"refresh_token","refresh_token":"<refresh_token>"}
→ 拿到新令牌对(旧 refresh 拉黑防重放)
3. 登出:GET /api/logout(当前 jti 拉黑)
```
::: tip 调试技巧
+ 开发环境把 `captcha.bypassCode`(默认 618618)作为 code 值可跳过验证码校验。
+ 令牌接口返回字段是 `access_token`(下划线),业务接口出入参是驼峰,这是唯一的命名例外。
+ 每次登录签发新令牌对,旧 access 仍有效直到过期或被拉黑;强退会双令牌一并拉黑。
:::