8、《5分钟构建RESTful API:Spring Boot Web开发入门》

5分钟构建RESTful API:Spring Boot Web开发入门

一、RESTful API核心认知

REST(Representational State Transfer)通过HTTP协议实现资源操作,其核心特征包括:

  1. 资源以URI标识(/api/users
  2. 通过HTTP方法表达操作语义(GET/POST/PUT/DELETE)
  3. 无状态通信
  4. 返回标准状态码(200/404/500等)

二、项目快速搭建

使用Spring Initializr创建项目:

<!-- pom.xml核心依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>

三、@RestController深度实践

3.1 基础控制器

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

    // 模拟内存数据库
    private Map<Long, User> users = new ConcurrentHashMap<>();
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }
}

3.2 完整CRUD示例

@PostMapping
public ResponseEntity<Void> createUser(@RequestBody User user) {
    users.put(user.getId(), user);
    return ResponseEntity.created(URI.create("/users/"+user.getId())).build();
}

@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
    if (!users.containsKey(id)) {
        return ResponseEntity.notFound().build();
    }
    users.put(id, user);
    return ResponseEntity.ok(user);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
    users.remove(id);
    return ResponseEntity.noContent().build();
}

四、统一响应封装

4.1 响应体标准化

@Data
public class ApiResponse<T> {
    private int code;       // 业务状态码
    private String message; // 提示信息
    private T data;         // 业务数据
    private long timestamp; // 响应时间戳

    public ApiResponse(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    // 快速构建成功响应
    public static <T> ApiResponse<T> success(T data) {
        return new ApiResponse<>(200, "Success", data);
    }
}

4.2 控制器改造示例

@GetMapping("/{id}")
    public ResponseEntity<ApiResponse<User>> getUser(@PathVariable Integer id) {
        User user = users.get(id);
        if (user == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(404, "User NOT exists", null));
        }
        return ResponseEntity.status(HttpStatus.OK)
                .body(ApiResponse.success(user));
    }

五、全局异常处理

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleGlobalException(Exception ex) {
        return new ApiResponse<>(500, "Server Error: " + ex.getMessage(), null);
    }
}

六、HTTP状态码精准控制

6.1 状态码使用规范

状态码使用场景
200 OK常规成功请求
201 Created资源创建成功
204 No Content成功无返回体
400 Bad Request请求参数错误
401 Unauthorized未认证
403 Forbidden无权限访问
404 Not Found资源不存在
500 Internal Server Error服务器内部错误

6.2 状态码实战应用

@PostMapping
public ResponseEntity<ApiResponse<User>> createUser(@Valid @RequestBody User user) {
    if (users.containsKey(user.getId())) {
        return ResponseEntity.status(HttpStatus.CONFLICT)
               .body(new ApiResponse<>(409, "User already exists", null));
    }
    users.put(user.getId(), user);
    return ResponseEntity.status(HttpStatus.CREATED)
           .body(ApiResponse.success(user));
}

项目结构参考:

src/main/java
└── com.example.demo
    ├── config        # 配置类
    ├── controller    # 控制器层
    ├── exception     # 自定义异常
    ├── model         # 数据模型
    └── response      # 响应封装
    └── Application   # 启动类

本文完整源码:

通过标准化响应封装、精确的状态码控制和全局异常处理,开发者可以快速构建出符合RESTful规范的健壮API。这种设计模式不仅提升接口的可维护性,更能显著降低前后端联调成本。后续可结合Spring Data JPA、Redis等组件构建完整的企业级应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wolf犭良

谢谢您的阅读与鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值