← 返回首页

RESTful API设计:构建规范的Web服务

📂 java ⏱ 1 min 183 words

RESTful API设计:构建规范的Web服务

概述

REST(Representational State Transfer)是一种软件架构风格,它定义了一组约束和原则,用于创建可扩展的Web服务。RESTful API是现代Web开发的标准。

1. HTTP方法语义

@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GetMapping
    public ResponseEntity<List<Product>> getAllProducts() {
        return ResponseEntity.ok(productService.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable Long id) {
        return productService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        Product created = productService.create(product);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(
            @PathVariable Long id, @RequestBody Product product) {
        return productService.update(id, product)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        if (productService.delete(id)) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }
}

2. URL设计规范

@RestController
@RequestMapping("/api/v1")
public class OrderController {

    @GetMapping("/orders")
    @GetMapping("/orders/{id}")
    @PostMapping("/orders")
    @PutMapping("/orders/{id}")
    @DeleteMapping("/orders/{id}")

    @GetMapping("/orders/{orderId}/items")
    @PostMapping("/orders/{orderId}/items")
    @GetMapping("/orders/{orderId}/items/{itemId}")
}

3. 状态码使用

public class ResponseHelper {
    public static <T> ResponseEntity<T> ok(T body) {
        return ResponseEntity.ok(body);
    }

    public static <T> ResponseEntity<T> created(T body) {
        return ResponseEntity.status(HttpStatus.CREATED).body(body);
    }

    public static ResponseEntity<ErrorResponse> badRequest(String message) {
        return ResponseEntity.badRequest()
            .body(new ErrorResponse("BAD_REQUEST", message));
    }

    public static ResponseEntity<ErrorResponse> notFound(String message) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse("NOT_FOUND", message));
    }
}

4. 版本控制

@RequestMapping("/api/v1/users")
public class UserControllerV1 {
}

@RequestMapping("/api/v2/users")
public class UserControllerV2 {
}

最佳实践

  1. 使用名词复数:/users而不是/user
  2. 合理使用HTTP方法:GET/POST/PUT/DELETE
  3. 使用标准状态码:200/201/400/404/500
  4. API版本控制:/api/v1/...
  5. 分页支持:/users?page=1&size=10

总结

RESTful API是现代Web开发的标准,遵循REST原则可以构建出可扩展、可维护的Web服务。掌握HTTP方法语义、URL设计规范和状态码使用,是设计高质量API的基础。