API 基础
REST 原则与资源思维。
API 基础
这一课你将能做到
- 说清楚 API 是什么、解决什么问题,以及它在前后端分离架构中的位置
- 用 curl 调用本站真实 API(
/api/lessons),并解读返回的 JSON 结构 - 理解资源(Resource)思维:把数据和能力抽象成可寻址的 URI
为什么要学
你写的每一个 Spring Boot Controller,本质上都是在设计 API。前端同事调你的接口、第三方系统对接你的服务、App 拉取数据——全靠 API。设计得好,调用方省心;设计得烂,天天被问「这个字段什么意思」「为什么又报 500」。
面试必问:REST 是什么?GET 和 POST 区别?幂等性怎么保证?这些不是背概念,是你每天都在做的事。
先建立图像
┌─────────┐ HTTP 请求 ┌─────────────┐ SQL ┌────────┐
│ 前端 │ ──────────────────► │ Spring Boot │ ─────────────► │ MySQL │
│ (React) │ ◄────────────────── │ Controller │ ◄───────────── │ │
└─────────┘ JSON 响应 └─────────────┘ └────────┘
API 就是中间这一层「契约」:前端不需要知道你怎么存数据,只需要知道「GET /api/lessons 能拿到课程列表」。
跟着做
步骤 1:调用本站真实 API
打开终端,执行:
curl -s http://localhost:8080/api/lessons | head -c 500
你会看到类似这样的 JSON:
{
"code": 200,
"message": "success",
"data": [
{
"id": 1,
"title": "Java 基础语法",
"slug": "java-basic-syntax",
"trackId": "java-fundamentals"
}
]
}
这就是 API 的「契约」:请求方发 HTTP 请求,服务方返回结构化数据。
步骤 2:写一个最简单的 Controller
@RestController
@RequestMapping("/api/lessons")
public class LessonController {
private final LessonService lessonService;
public LessonController(LessonService lessonService) {
this.lessonService = lessonService;
}
@GetMapping
public ApiResponse<List<Lesson>> list() {
List<Lesson> lessons = lessonService.findAll();
return ApiResponse.success(lessons);
}
@GetMapping("/{id}")
public ApiResponse<Lesson> getById(@PathVariable Long id) {
Lesson lesson = lessonService.findById(id);
return ApiResponse.success(lesson);
}
}
@RestController = @Controller + @ResponseBody,表示这个类处理 HTTP 请求并直接返回 JSON,不渲染页面。
步骤 3:理解资源思维
把「课程」看作资源:
| 操作 | HTTP 方法 | URI | 含义 |
|---|---|---|---|
| 查询列表 | GET | /api/lessons | 获取所有课程 |