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

接口(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接口。

http://www.xdnf.cn/news/5968.html

相关文章:

  • DELL R770 服务器,更换RAID卡教程!
  • 注释之CR
  • InitVerse节点部署教程
  • flutter编译时 设置jdk版本
  • 电子电器架构 --- 区域计算架构(Zonal Compute)备战下一代电子电气架构
  • 什么是SparkONYarn模式
  • 《量子语言模型研究综述》核心解读
  • Windows下安装mysql8.0
  • ridecore流水线解读
  • 后端系统做国际化改造,生成多语言包
  • ai agent(智能体)开发 python高级应用1:Crawl4AI 如何通过ollama 给本地大模型插上网络翅膀
  • HarmonyOS 【诗韵悠然】AI古诗词赏析APP开发实战从零到一系列(二、项目准备与后台服务搭建)
  • Linux操作系统之进程(一):进程属性与进程创建
  • 算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
  • Java-集合
  • React中的状态管理Dva总结
  • 改变应用的安装目录
  • texlive 与 Texmaker 安装
  • 在Babylon.js中实现完美截图:包含Canvas和HTML覆盖层
  • [论文阅读]ControlNET: A Firewall for RAG-based LLM System
  • 面试篇:MySQL
  • c# 数据结构 树篇 入门树与二叉树的一切
  • Glowroot安装使用第一期
  • 从零开始了解数据采集(二十七)——什么IIOT平台
  • 导出导入Excel文件(详解-基于EasyExcel)
  • Python操作Excel文件全攻略:xls/xlsx处理从入门到精通
  • 【数据结构】栈
  • 深度学习---获取模型中间层输出的意义
  • VSCode设置SSH免密登录
  • 大型系统开发底座:ivX 研发基座技术架构与协作机制剖析