0X03 RESTFul API & Swagger

发布时间 2023-08-11 20:51:44作者: Icfh

Restful API风格

RESTful是目前流行的互联网软件服务架构设计风格。

  • 每一个URI代表一种资源
  • 客户端使用GET、POST、PUT、DELETE四种表示操作方式的动词对服务端资源进行操作:GET用于获取资源,POST用于新建资源(也可以用于更新资源),PUT用于更新资源,DELETE用于删除资源。
  • 通过操作资源的表现形式来实现服务端请求操作。
  • 资源的表现形式是JSON或者HTML
  • 客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都包含必需的信息。

例子:

比如说删除用户:

传统风格:GET http://127.0.0.1:8888/del?id=10

Restful风格:DELETE http://127.0.0.1:8888/user/10

使用注解完成Restful API实现

SpringBoot提供的spring-boot-starter-web组件完全支持开发RESTful API

提供了与REST操作方式(GET、POST、PUT、DELETE)对应的注解

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

小demo,业务逻辑直接用文本内容代替

package com.example.icfh_springboot1.controller;

import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable int id){
        return "GET User by id:"+id;
    }

    @PostMapping("/user")
    public String saveUser(){
        return "POST User";
    }

    @PutMapping("/user")
    public String updateUser(){
        return "Update User";
    }

    @DeleteMapping("/user/{id}")
    public String deleteUserById(@PathVariable int id){
        return "Delete User"+id;
    }

}

Swagger

在实际开发过程中,后端的开发往往是多个人的,而向前端描述后端的接口就成了需要规范和统一的事务。

那么也就有了Swagger这种框架。

  • Swagger是一个规范和完整的框架,用于生成、描述和可视化RESTful风格的web服务,是非常流行的API表达式工具。
  • Swagger可以自动生成完善的RESTful API文档,同时并根据后台代码修改同步更新,同时提供完整的测试页面来调试API。

porm.xml中导入相关依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

在我们的SpringBoot项目中,需要先写一个Swagger的配置

package com.example.icfh_springboot1.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer{
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }
    /*
    * 配置Swagger2相关的bean
    */

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Test Demo")
                .description("Study")
                .build();
    }

}

访问swagger-ui.html页面即可

image-20230808232016011