RESTful服务+swagger

 

RESTful风格

介绍

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

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

两个关键特性:

  • 安全性:当我们使用GET操作获取资源时,不会引起资源本身的改变,也不会引起服务器状态的改变。
  • 幂等性:幂等的方法保证了重复进行一个请求和一次请求的效果相同

状态码分为以下5个类别:

  • 1xx:信息,通信传输协议级信息
  • 2xx:成功,表示客户端的请求已成功
  • 3xx:重定向,表示客户端必须执行一些其他操作才能完成其请求
  • 4xx:客户端错误,此类错误状态码指向客户端
  • 5xx:服务器错误,服务器负责这写错误状态码

Spring Boot实现RESTful API

package com.example.helloworld.controller;

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

/**
 * @Author Fxdll
 * @Date 2024/5/3 23:13
 * @PackageName:com.example.helloworld.controller
 * @ClassName: UserController
 * @Description: TODO
 * @Version 1.0
 */
@RestController
public class UserController {
    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable("id") int id) {    // 定义一个接口,返回字符串
        System.out.println( id);
        return "根据id查询用户成功!";
    }
    @PostMapping("/user")
    public String saveUser() {    // 定义一个接口,返回字符串
        return "添加用户成功!";
    }
    @PutMapping("/user")
    public String updateUser() {    // 定义一个接口,返回字符串
        return "更新用户成功!";
    }
    @DeleteMapping("/user/{id}")
    public String deleteUser(@PathVariable("id") int id) {    // 定义一个接口,返回字符串
        System.out.println(id);
        return "删除用户成功!";
    }
}

@GetMapping:处理GET请求,获取资源。

@PostMapping:处理POST请求,新增资源。

@PutMapping:处理PUT请求,更新资源。

@DeleteMapping:处理DELETE请求,删除资源。

@PatchMapping:处理PATCH请求,用于部分更新资源。

Swagger

Swagger能够自动生成完善的RESTful API文档,同时并根据后台代码的修改同步更新,同时提供完整的测试页面来调试API。

导入依赖

 <!-- Swagger添加swagger2相关依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- Swagger添加swagger-ui相关依赖 -->   
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

创建配置类

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

package com.example.helloworld.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 * @Author Fxdll
 * @Date 2024/5/3 23:25
 * @PackageName:com.example.helloworld.config
 * @ClassName: SwaggerConfig
 * @Description: TODO
 * @Version 1.0
 */
@Configuration  // 声明这是配置类
@EnableSwagger2// 启用Swagger2
public class SwaggerConfig {
    // 这里可以添加swagger2的配置
    // 例如:
    // 配置swagger2的标题、描述、版本等信息
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis
                        (RequestHandlerSelectors.basePackage("com")) // 指定controller的包名
                .paths(PathSelectors.any()) // 指定请求路径
                .build();
    }
    /*
     *此处主要是API文档页面显示信息
     */
    // @Bean
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("演示项目API")   // 标题
                .description("演示项目")  // 描述
                .version("1.0")  // 版本
                .build();
    }
}
@Controller
@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);
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // com包下所有API都交给Swagger2管理
                .apis(RequestHandlerSelectors.basePackage("com"))
                .paths(PathSelectors.any()).build();
    }

      API文档页面显示信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("演示项目")
                .description("学习")
                .build();
    }
}

最后访问:http://localhost:8080/swagger-ui.html即可

我的最后效果:

可以在方法上添加注释 会在swagger显示

也可以点击进行测试

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值