← 返回首页 ❓ 面试题库
📑 本篇章节导航 (共7章,点击直达)
一、RESTful设计原则二、接口幂等性三、参数校验四、API版本管理五、接口文档六、高频综合题面试速记口诀

Q106 API设计与RESTful最佳实践实战

20K Java+AI 岗位高频考点 — API是系统对外的窗口,设计质量直接影响团队效率和用户体验。覆盖RESTful规范、接口幂等性、版本管理、统一响应、参数校验、异常处理、接口文档等。

一、RESTful设计原则

1. REST的核心约束?

2. RESTful URL设计规范?


✅ 好的设计:
GET    /api/v1/users           # 用户列表
GET    /api/v1/users/123       # 获取用户
POST   /api/v1/users           # 创建用户
PUT    /api/v1/users/123       # 更新用户(全量)
PATCH  /api/v1/users/123       # 更新用户(部分)
DELETE /api/v1/users/123       # 删除用户
GET    /api/v1/users/123/orders # 用户的订单列表

❌ 坏的设计:
GET    /api/getUser?id=123
POST   /api/deleteUser
POST   /api/updateUser
GET    /api/userList

规则:

3. HTTP状态码的正确使用?

状态码含义使用场景
200OKGET/PUT/PATCH成功
201CreatedPOST创建成功
204No ContentDELETE成功
400Bad Request参数校验失败
401Unauthorized未认证
403Forbidden无权限
404Not Found资源不存在
409Conflict资源冲突(重复创建)
422Unprocessable Entity业务规则校验失败
429Too Many Requests限流
500Internal Server Error服务器内部错误

4. 统一响应格式?


@Data
public class ApiResponse<T> {
    private int code;        // 业务码(200=成功,其他=失败)
    private String message;  // 提示信息
    private T data;          // 数据
    private long timestamp;

    public static <T> ApiResponse<T> ok(T data) {
        ApiResponse<T> r = new ApiResponse<>();
        r.setCode(200);
        r.setMessage("success");
        r.setData(data);
        r.setTimestamp(System.currentTimeMillis());
        return r;
    }

    public static <T> ApiResponse<T> error(int code, String message) {
        ApiResponse<T> r = new ApiResponse<>();
        r.setCode(code);
        r.setMessage(message);
        r.setTimestamp(System.currentTimeMillis());
        return r;
    }
}

// 分页响应
@Data
public class PageResponse<T> {
    private List<T> items;
    private long total;
    private int page;
    private int size;
    private int totalPages;
}

二、接口幂等性

5. 什么是幂等性?哪些HTTP方法天然幂等?

幂等:同一操作执行1次或N次,结果相同。

HTTP方法幂等性说明
GET✅查询不改变状态
PUT✅全量替换,结果相同
DELETE✅删除同一资源,结果相同
PATCH⚠️部分更新需注意
POST❌每次创建可能产生新资源

6. POST接口如何保证幂等?

方案一:Token机制


// 1. 获取幂等Token
@GetMapping("/token")
public String getToken() {
    String token = UUID.randomUUID().toString();
    redisTemplate.opsForValue().set("idempotent:" + token, "1", 10, TimeUnit.MINUTES);
    return token;
}

// 2. 提交时携带Token
@PostMapping("/orders")
@Idempotent  // 自定义注解
public ApiResponse<OrderDTO> createOrder(@RequestHeader("X-Idempotent-Token") String token,
                                          @RequestBody CreateOrderRequest request) {
    // Token验证+删除(原子操作)
    Boolean deleted = redisTemplate.delete("idempotent:" + token);
    if (!deleted) {
        throw new BusinessException("请勿重复提交");
    }
    return ApiResponse.ok(orderService.create(request));
}

方案二:唯一业务键


@PostMapping("/orders")
public ApiResponse<OrderDTO> createOrder(@RequestBody CreateOrderRequest request) {
    String uniqueKey = request.getUserId() + ":" + request.getRequestId();
    try {
        return ApiResponse.ok(orderService.createWithIdempotent(request, uniqueKey));
    } catch (DuplicateKeyException e) {
        // 唯一约束冲突 → 已创建过
        return ApiResponse.ok(orderService.findByUniqueKey(uniqueKey));
    }
}

方案三:乐观锁


@PatchMapping("/orders/{id}/status")
public ApiResponse<Void> updateStatus(@PathVariable Long id, @RequestBody StatusUpdateRequest req) {
    int updated = orderMapper.updateStatus(id, req.getStatus(), req.getVersion());
    if (updated == 0) {
        throw new OptimisticLockException("数据已被修改,请刷新重试");
    }
    return ApiResponse.ok(null);
}

7. 自定义幂等注解?


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
    int expireSeconds() default 600;
}

@Aspect
@Component
public class IdempotentAspect {
    @Autowired StringRedisTemplate redisTemplate;

    @Around("@annotation(idempotent)")
    public Object around(ProceedingJoinPoint pjp, Idempotent idempotent) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader("X-Idempotent-Token");
        if (token == null) {
            throw new BusinessException("缺少幂等Token");
        }

        Boolean success = redisTemplate.opsForValue()
            .setIfAbsent("idempotent:" + token, "1", idempotent.expireSeconds(), TimeUnit.SECONDS);
        if (!success) {
            throw new BusinessException("请勿重复提交");
        }

        return pjp.proceed();
    }
}

三、参数校验

8. Spring Boot参数校验最佳实践?


// DTO校验
public record CreateOrderRequest(
    @NotNull(message = "用户ID不能为空")
    Long userId,

    @NotEmpty(message = "商品列表不能为空")
    @Size(max = 100, message = "最多100种商品")
    List<@Valid OrderItemRequest> items,

    @DecimalMin(value = "0.01", message = "金额必须大于0")
    BigDecimal amount,

    @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
    String phone,

    @Email(message = "邮箱格式不正确")
    @Nullable String email
) {}

public record OrderItemRequest(
    @NotNull Long productId,
    @Min(value = 1, message = "数量至少1") @Max(value = 999, message = "数量最多999")
    Integer quantity
) {}

// Controller
@PostMapping("/orders")
public ApiResponse<OrderDTO> create(@Valid @RequestBody CreateOrderRequest request) { ... }

9. 自定义校验注解?


@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = EnumValidator.class)
public @interface EnumValue {
    Class<? extends Enum<?>> enumClass();
    String message() default "值不在允许范围内";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class EnumValidator implements ConstraintValidator<EnumValue, String> {
    private Set<String> acceptedValues;

    @Override
    public void initialize(EnumValue annotation) {
        acceptedValues = Arrays.stream(annotation.enumClass().getEnumConstants())
            .map(Enum::name).collect(Collectors.toSet());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return value == null || acceptedValues.contains(value);
    }
}

// 使用
public record UpdateRequest(
    @EnumValue(enumClass = OrderStatus.class, message = "无效的订单状态")
    String status
) {}

10. 全局异常处理器?


@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<Void> handleValidation(MethodArgumentNotValidException ex) {
        String message = ex.getFieldErrors().stream()
            .map(e -> e.getField() + ": " + e.getDefaultMessage())
            .collect(Collectors.joining("; "));
        return ApiResponse.error(400, message);
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    public ApiResponse<Void> handleBusiness(BusinessException ex) {
        return ApiResponse.error(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleException(Exception ex) {
        log.error("未处理异常", ex);
        return ApiResponse.error(500, "系统异常,请稍后重试");
    }
}

四、API版本管理

11. API版本控制的方案?

方案示例优点缺点
URI路径/api/v1/users直观、简单URL变化
HeaderX-API-Version: 1URL不变不直观
参数/api/users?version=1简单污染参数
Content-Typeapplication/vnd.myapi.v1+jsonRESTful复杂

推荐:URI路径版本(/api/v1/),最直观,业界主流。

12. 版本迁移的最佳实践?


// 方案:同一Controller支持多版本
@RestController
@RequestMapping("/api")
public class UserController {
    @GetMapping("/v1/users/{id}")
    public UserV1DTO getUserV1(@PathVariable Long id) { ... }

    @GetMapping("/v2/users/{id}")
    public UserV2DTO getUserV2(@PathVariable Long id) { ... }
}

迁移策略:

1. 新版本并行运行

2. 通知客户端迁移

3. 监控旧版本调用量

4. 旧版本调用量为0后下线(给3-6个月缓冲)


五、接口文档

13. Swagger/OpenAPI 3.0集成?


// Spring Boot 3.x + SpringDoc
@Tag(name = "订单管理", description = "订单CRUD接口")
@RestController
@RequestMapping("/api/v1/orders")
public class OrderController {

    @Operation(summary = "创建订单", description = "创建新订单并返回订单详情")
    @ApiResponses({
        @ApiResponse(responseCode = "201", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "参数错误"),
        @ApiResponse(responseCode = "409", description = "重复创建")
    })
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public ApiResponse<OrderDTO> createOrder(
        @Parameter(description = "创建订单请求") @Valid @RequestBody CreateOrderRequest request) {
        return ApiResponse.ok(orderService.create(request));
    }
}

# application.yml
springdoc:
  api-docs:
    path: /v3/api-docs
  swagger-ui:
    path: /swagger-ui.html
    tags-sorter: alpha
    operations-sorter: method

六、高频综合题

14. 如何设计一个对外OpenAPI?


API网关:鉴权(API Key/OAuth2) + 限流 + 日志
接口规范:RESTful + 统一响应 + 版本管理
安全机制:签名验证 + HTTPS + 幂等Token
文档:OpenAPI 3.0自动生成 + 在线调试
SDK:提供Java/Python/Go多语言SDK
沙箱环境:供开发者测试

15. 如何设计接口的限流策略?


// 滑动窗口限流(Redis + Lua)
public boolean isAllowed(String key, int maxRequests, int windowSeconds) {
    String script = """
        local current = redis.call('TIME')
        local now = tonumber(current[1]) * 1000 + math.floor(tonumber(current[2]) / 1000)
        local window = tonumber(ARGV[2]) * 1000
        redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - window)
        local count = redis.call('ZCARD', KEYS[1])
        if count < tonumber(ARGV[1]) then
            redis.call('ZADD', KEYS[1], now, now .. ':' .. math.random())
            redis.call('PEXPIRE', KEYS[1], window)
            return 1
        end
        return 0
        """;
    Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
        List.of(key), String.valueOf(maxRequests), String.valueOf(windowSeconds));
    return result != null && result == 1;
}

16. HATEOAS是什么?

HATEOAS(Hypermedia as the Engine of Application State)是REST的约束之一,响应中包含相关资源的链接:


{
  "id": 123,
  "name": "张三",
  "_links": {
    "self": { "href": "/api/v1/users/123" },
    "orders": { "href": "/api/v1/users/123/orders" }
  }
}

17. 如何保证接口的向后兼容?

兼容的变更:

不兼容的变更(需要新版本):

18. Long类型ID的精度丢失问题?

JavaScript的Number最大安全整数是2^53-1,Java的Long可以到2^63-1。

解决方案:Long序列化为String。


@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, new ToStringSerializer());
        module.addSerializer(Long.TYPE, new ToStringSerializer());
        mapper.registerModule(module);
        return mapper;
    }
}

19. 如何处理大批量数据导出接口?


@GetMapping("/orders/export")
public void export(HttpServletResponse response) {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=orders.csv");

    try (OutputStream out = response.getOutputStream();
         PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
        // 写BOM(Excel兼容)
        out.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});

        // 流式查询,避免OOM
        orderMapper.streamAll(order -> {
            writer.println(toCsvLine(order));
            writer.flush();
        });
    }
}

20. API网关的设计?


客户端 → API网关
         ├── 认证鉴权(JWT/OAuth2)
         ├── 限流熔断
         ├── 请求日志
         ├── 协议转换(REST → gRPC)
         ├── 灰度路由
         └── 响应缓存
              ↓
         后端微服务

面试速记口诀

RESTful三原则:资源用名词、操作用HTTP方法、响应用状态码

>

幂等三方案:Token机制、唯一业务键、乐观锁版本号

>

版本三方案:URI路径(推荐)、Header、Content-Type

>

接口四要素:统一响应、参数校验、异常处理、接口文档