Java 后端 / 系统课时

设计 REST 资源与路由

设计 REST 资源与路由

本课解决 REST 接口路径随意、动作混乱和状态码不一致的问题。你将从业务资源出发设计路由,并用一个可运行的 Spring Boot 3 示例验证创建、查询和删除接口。

学习目标

  • 将业务对象建模为清晰、稳定的 REST 资源
  • 正确组合 HTTP 方法、资源路径和状态码
  • 使用 Spring MVC 实现并验证一组一致的接口

先定义资源,再定义动作

REST 路由应围绕名词资源设计,而不是把操作名堆进路径。用户集合可以表示为 /api/users,单个用户表示为 /api/users/{id}。创建、查询和删除由 HTTP 方法表达,不再使用 /createUser、/getUser 或 /deleteUser。

资源路径应保持复数形式、层级清晰和命名稳定。只有存在明确从属关系时才使用嵌套路径,例如 /api/users/{userId}/orders。嵌套层级过深会增加耦合,通常控制在两到三层以内。

统一方法与状态码

业务意图 HTTP 方法 路径 成功状态码
创建用户 POST /api/users 201 Created
查询用户 GET /api/users/{id} 200 OK
替换用户 PUT /api/users/{id} 200 OK 或 204 No Content
局部修改 PATCH /api/users/{id} 200 OK 或 204 No Content
删除用户 DELETE /api/users/{id} 204 No Content

创建成功时应返回 201 Created,并通过 Location 响应头指出新资源地址。资源不存在通常返回 404 Not Found;请求格式不合法返回 400 Bad Request;重复创建造成业务冲突时可返回 409 Conflict。

实现一组最小 REST 接口

下面示例使用内存集合保存数据,便于集中观察路由与响应语义。它是完整可运行的启动类,依赖 spring-boot-starter-web,不包含数据库持久化。

java
package com.example.restapi;

import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@SpringBootApplication
public class RestApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestApiApplication.class, args);
    }

    record CreateUserRequest(String name) {}
    record UserResponse(long id, String name) {}

    @RestController
    @RequestMapping("/api/users")
    static class UserController {

        private final AtomicLong sequence = new AtomicLong(1000);
        private final Map<Long, UserResponse> users = new ConcurrentHashMap<>();

        @PostMapping
        ResponseEntity<UserResponse> create(@RequestBody CreateUserRequest request) {
            long id = sequence.incrementAndGet();
            UserResponse user = new UserResponse(id, request.name());
            users.put(id, user);

            // Location 指向刚创建的资源,而不是集合地址
            URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{id}")
                    .buildAndExpand(id)
                    .toUri();
            return ResponseEntity.created(location).body(user);
        }

        @GetMapping("/{id}")
        ResponseEntity<UserResponse> find(@PathVariable long id) {
            UserResponse user = users.get(id);
            return user == null
                    ? ResponseEntity.notFound().build()
                    : ResponseEntity.ok(user);
        }

        @DeleteMapping("/{id}")
        ResponseEntity<Void> delete(@PathVariable long id) {
            return users.remove(id) == null
                    ? ResponseEntity.notFound().build()
                    : ResponseEntity.noContent().build();
        }
    }
}

预期结果

text
应用启动后提供 POST /api/users、GET /api/users/{id} 和 DELETE /api/users/{id}。
创建成功返回 201 与 Location;查询成功返回 200;删除成功返回 204。

启动应用后执行以下命令;<PORT> 替换为实际端口。首次创建得到的实际 ID 可能不同,后续查询应使用响应体中的 ID。

bash
curl -i -X POST "http://localhost:<PORT>/api/users" \
  -H "Content-Type: application/json" \
  -d '{"name":"Ada"}'

curl -i "http://localhost:<PORT>/api/users/<ID>"

预期输出

text
HTTP/1.1 201
Location: http://localhost:<PORT>/api/users/<ID>
Content-Type: application/json

{"id":<ID>,"name":"Ada"}

HTTP/1.1 200
Content-Type: application/json

{"id":<ID>,"name":"Ada"}

响应头可能包含日期、连接方式等附加字段;验收时重点检查状态码、Location、媒体类型和资源表示。

处理边界而不污染路由

筛选、分页和排序属于集合查询条件,应放在查询参数中,例如 /api/users?status=active&page=0&size=20,而不是创建 /api/users/active/page/0。对同一资源执行特殊业务动作时,可谨慎使用子资源,例如 /api/orders/{id}/cancellation。

接口版本应优先通过兼容演进解决;确需破坏性升级时,可采用 /api/v1/users。无论选择哪种方式,都应在同一服务内保持一致,避免部分接口放路径版本、部分接口放自定义请求头。

错误响应也应统一结构,至少包含可机器识别的错误码、面向用户的消息和请求追踪标识。这样客户端不必针对每个控制器编写不同解析逻辑。

REST 路由验收清单

检查路由时,先确认路径表达资源而非动作,再确认 HTTP 方法是否符合语义。随后检查成功与失败状态码、Content-Type、Location 和空响应体是否一致。

还要验证幂等性:重复执行同一个 GET、PUT 或 DELETE 不应产生额外副作用;POST 通常不保证幂等。路由设计通过这些约束后,控制器实现和接口文档才容易长期维护。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

设计 REST 资源与路由

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通