当前位置: 首页 > news >正文

接口(API)开发核心知识点

接口(API)开发核心知识点

一、API基础概念

1. 什么是API

  • API (Application Programming Interface):应用程序编程接口
  • Web API:基于HTTP协议的接口,用于系统间数据交互
  • RESTful API:符合REST架构风格的API设计

2. API设计原则

  • 统一接口:使用标准HTTP方法(GET, POST, PUT, DELETE等)
  • 无状态:每个请求包含处理所需的所有信息
  • 资源导向:URI指向资源而非动作
  • 表述性:资源与表现形式分离(JSON/XML等)

二、RESTful API设计规范

1. 资源命名

  • 使用名词复数形式表示资源:

    /users        # 用户集合
    /users/123    # ID为123的用户
    /users/123/orders  # 用户123的订单
    

2. HTTP方法使用

方法描述示例
GET获取资源GET /users
POST创建资源POST /users
PUT全量更新资源PUT /users/123
PATCH部分更新资源PATCH /users/123
DELETE删除资源DELETE /users/123
HEAD获取资源元数据HEAD /users

3. 状态码规范

状态码含义
200OK - 成功
201Created - 创建成功
204No Content - 无内容
400Bad Request - 请求错误
401Unauthorized - 未授权
403Forbidden - 禁止访问
404Not Found - 资源不存在
500Server Error - 服务器错误

4. 请求/响应设计

  • 请求头

    Accept: application/json
    Content-Type: application/json
    Authorization: Bearer <token>
    
  • 请求体(JSON示例):

    {"username": "john_doe","email": "john@example.com"
    }
    
  • 响应体(JSON示例):

    {"status": "success","data": {"id": 123,"username": "john_doe"},"message": "User created successfully"
    }
    

三、API开发技术栈

1. Java常用框架

  • Spring Boot:快速构建API服务
  • Spring MVC:处理HTTP请求/响应
  • JAX-RS:Java API for RESTful Web Services
  • Swagger/OpenAPI:API文档生成

2. 数据库访问

  • JDBC:Java数据库连接
  • JPA/Hibernate:ORM框架
  • MyBatis:SQL映射框架
  • Spring Data:简化数据访问

3. 安全认证

  • Basic Auth:基本认证
  • JWT:JSON Web Token
  • OAuth2:开放授权协议
  • Spring Security:安全框架

四、Spring Boot实现API示例

1. 控制器示例

@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;// 获取用户列表@GetMappingpublic ResponseEntity<List<User>> getAllUsers() {return ResponseEntity.ok(userService.findAll());}// 获取单个用户@GetMapping("/{id}")public ResponseEntity<User> getUserById(@PathVariable Long id) {return userService.findById(id).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());}// 创建用户@PostMappingpublic ResponseEntity<User> createUser(@Valid @RequestBody User user) {User savedUser = userService.save(user);URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedUser.getId()).toUri();return ResponseEntity.created(location).body(savedUser);}// 更新用户@PutMapping("/{id}")public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody User user) {return ResponseEntity.ok(userService.update(id, user));}// 删除用户@DeleteMapping("/{id}")public ResponseEntity<Void> deleteUser(@PathVariable Long id) {userService.delete(id);return ResponseEntity.noContent().build();}
}

2. 统一响应封装

public class ApiResponse<T> {private String status;private T data;private String message;// 构造方法、getter/setter省略public static <T> ApiResponse<T> success(T data) {return new ApiResponse<>("success", data, null);}public static ApiResponse<?> error(String message) {return new ApiResponse<>("error", null, message);}
}

3. 全局异常处理

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<ApiResponse<?>> handleNotFound(ResourceNotFoundException ex) {return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ApiResponse.error(ex.getMessage()));}@ExceptionHandler(MethodArgumentNotValidException.class)public ResponseEntity<ApiResponse<?>> handleValidation(MethodArgumentNotValidException ex) {List<String> errors = ex.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());return ResponseEntity.badRequest().body(ApiResponse.error(errors.toString()));}@ExceptionHandler(Exception.class)public ResponseEntity<ApiResponse<?>> handleAll(Exception ex) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.error("Internal server error"));}
}

五、API安全

1. JWT认证实现

// JWT工具类
public class JwtTokenUtil {private static final String SECRET = "your-secret-key";private static final long EXPIRATION = 86400000; // 24小时public static String generateToken(UserDetails userDetails) {return Jwts.builder().setSubject(userDetails.getUsername()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION)).signWith(SignatureAlgorithm.HS512, SECRET).compact();}public static String getUsernameFromToken(String token) {return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody().getSubject();}public static boolean validateToken(String token, UserDetails userDetails) {final String username = getUsernameFromToken(token);return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));}private static boolean isTokenExpired(String token) {Date expiration = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody().getExpiration();return expiration.before(new Date());}
}

2. Spring Security配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/api/auth/**").permitAll().anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().addFilter(new JwtAuthenticationFilter(authenticationManager())).addFilter(new JwtAuthorizationFilter(authenticationManager()));}@Overridepublic void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

六、API文档

1. Swagger配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket api() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("com.example.api")).paths(PathSelectors.any()).build().apiInfo(apiInfo());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("API Documentation").description("API reference for developers").version("1.0").build();}
}

2. OpenAPI 3.0配置

@Configuration
public class OpenApiConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("API Documentation").version("1.0").description("API reference for developers").license(new License().name("Apache 2.0"))).externalDocs(new ExternalDocumentation().description("API Wiki Documentation").url("https://example.com/docs"));}
}

七、API测试

1. Postman测试

  • 请求示例

    GET http://localhost:8080/api/users
    Headers:Authorization: Bearer <token>Accept: application/json
    

2. 单元测试示例

@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {@Autowiredprivate MockMvc mockMvc;@Testvoid shouldReturnAllUsers() throws Exception {mockMvc.perform(get("/api/users").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(2)));}@Testvoid shouldCreateUser() throws Exception {String userJson = "{\"username\":\"test\",\"email\":\"test@example.com\"}";mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(userJson)).andExpect(status().isCreated()).andExpect(jsonPath("$.username").value("test"));}
}

八、API性能优化

1. 缓存策略

  • 客户端缓存Cache-Control
  • 服务端缓存:Redis, Memcached
  • 数据库缓存:查询缓存

2. 分页与限流

  • 分页参数

    GET /api/users?page=1&size=20
    
  • 限流实现

    @RateLimiter(value = 10, key = "#userId") // 每秒10次
    @GetMapping("/api/users/{userId}")
    public ResponseEntity<User> getUser(@PathVariable String userId) {// ...
    }
    

3. 异步处理

@Async
public CompletableFuture<User> getUserAsync(Long id) {return CompletableFuture.completedFuture(userRepository.findById(id).orElse(null));
}

九、微服务API网关

1. Spring Cloud Gateway

spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/api/users/**filters:- StripPrefix=1

2. 常见网关功能

  • 路由转发
  • 负载均衡
  • 熔断降级
  • 权限验证
  • 请求限流
  • 日志监控

以上是API开发的核心知识点,涵盖了设计规范、实现技术、安全认证、文档生成和性能优化等方面,掌握这些内容可以开发出高质量、安全可靠的API接口。

相关文章:

  • Qt —— 使用Enigma Virtual Box将Qt程序打包为独立可运行exe(附:完整打包方法且完美运行)
  • CSRF防范歪招
  • 分区器介绍
  • Java集合框架详解与使用场景示例
  • PyInstaller 打包后 Excel 转 CSV 报错解决方案:“excel file format cannot be determined“
  • uniapp(vue3)动态计算swiper高度封装自定义hook
  • Foupk3systemX5OS TXW8移动设备
  • UE5中制作动态数字Decal
  • While语句数数字
  • 互信息:揭秘变量间的隐藏关联
  • 5.13本日总结
  • windows 强行终止进程,根据端口号
  • 【Linux 系统调试】系统的动态跟踪工具--SystemTap
  • 系统平衡与企业挑战
  • C++ 字符格式化输出
  • Linux 系统安全基线检查:入侵防范测试标准与漏洞修复方法
  • 【递归、搜索与回溯】专题一:递归(二)
  • SparkSQL 连接 MySQL 并添加新数据:实战指南
  • 微服务八股(自用)
  • hashicorp vault机密管理系统的国产化替代:安当SMS凭据管理系统,量子安全赋能企业密钥管理
  • 梅花奖在上海丨陈丽俐“婺剧折戏专场”:文戏武做,武戏文唱
  • 北京航空航天大学首个海外创新研究院落户巴西
  • 沙县小吃中东首店在沙特首都利雅得开业,首天营业额5万元
  • 巴基斯坦全国航班仍持续延误或取消
  • 印控克什米尔地区再次传出爆炸声
  • 巴基斯坦空袭印度多地空军基地,巴战机进入印领空