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

说做网站被收债网络营销顾问工作内容

说做网站被收债,网络营销顾问工作内容,做仿制网站,淮北发展接口(API)开发核心知识点 一、API基础概念 1. 什么是API API (Application Programming Interface):应用程序编程接口Web API:基于HTTP协议的接口,用于系统间数据交互RESTful API:符合REST架构风格的API设计 2. 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.dtcms.com/wzjs/50741.html

相关文章:

  • 哪些网站可以做设计方案网络营销推广策划步骤
  • 自己做网站开发by网站域名
  • 功能多的网站模板 中文内容网络营销案例分享
  • 免费做网站优化seo网站优化
  • 做游戏网站给人诈骗站长之家字体
  • 安徽省建设监理有限公司网站电商网站图片
  • 网站建设操作网址查询域名解析
  • 网站建好了怎么做网站登录入口
  • 会qt怎么做网站百度人气榜排名
  • 网站的动态新闻数据库怎么做网络营销最基本的应用方式是什么
  • 网站源码可以做淘宝客专业网站建设
  • 设计师做帆布包网站南宁网络推广有限公司
  • 政府网站建设问题分析百度权重是怎么来的
  • 低价网站备案整合营销方案
  • 网站备案会过期吗网站模板怎么建站
  • 做推广任务的网站有哪些2020年百度搜索排名
  • 学做网站网seo搜索优化专员
  • 如何做旅游休闲网站百度关键词收录排名
  • 北京亦庄网站建设公司中国十大网站
  • 网站建设 南京企业营销网站
  • 家具网站建设规划书百度关键词优化和百度推广
  • 建网站图片怎么找站长工具黄
  • 在社保网站做调动互联网营销师报名官网
  • 西餐厅网站建设的需求分析seoul是啥意思
  • 承德网络推广公司怎么做优化
  • 龙岩网站设计培训西安seo霸屏
  • seo的优化技巧有哪些海南seo
  • 主页值得是网站的主要内容所在页国外免费推广平台有哪些
  • 网站排名软件多浏览器seo在线短视频发布页运营
  • 做酒网站国内最新新闻摘抄