来源:蜘蛛抓取(WebSpider)
时间:2017-12-26 22:14
标签:
wifi无线信道
在rails项目中使用Swagger&UI生成可视化api
swagger-docs
/richhollis/swagger-docs
swagger-docs-sample:&&
/richhollis/swagger-docs-sample/blob/master/README.md
swagger-ui: /wordnik/swagger-ui
1、vim Gemfile 添加& gem 'swagger-docs' 然后
bundle&&& 或者直接
gem install swagger-docs
2、cd rails项目目录;&& vim config/initializers/swagger_docs.rb , 并添加保存如下内容:
&Swagger::Docs::Config.register_apis({
&&& "1.0" =& {:base_path =& "http://localhost:3000", :api_file_path =& "public"}
3、在某个controller中添加:
&& swagger_controller :user_api, "UserApi"
&& swagger_api :index do
&&& summary "test"
&&& response :unauthorized
&&& response :not_acceptable
&& def index
&&&& render :json =& {result:"Success"}, :status =& 200
4、rake swagger:docs
5、rails s
6、cd public
7、git clone /wordnik/swagger-ui.git
8、vim swagger-ui/dist/index.html
&& 将 url 修改为 http://localhost:3000/api-docs.json
&& window.swaggerUi = new SwaggerUi({
&&&&& url: "http://localhost:3000/api-docs.json",
&&&&&&&&&& //http://petstore./api/api-docs&&&&&
&&&&& dom_id: "swagger-ui-container",
&&&&& supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
&&&&& ... ... ...
9、浏览器中输入 http://localhost:3000/swagger-ui/dist/index.html
即可查看并测试api
如果页面打开慢,vim public/swagger-ui/dist/index.html ,
将 .../css...这行代码注释掉。
注: config/routes.rb 中 swagger对应的route 不要用match, 否则会报错
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。采用swagger ui可实现接口可视化,脱离写接口文档的痛苦,及避免不厌其烦地解说各接口需要的参数和返回结果
一、什么是swagger
Swagger的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。类似于低级编程接口,Swagger去掉了调用服务时的很多猜测。
二、swagger的优势
1.整体文档界面清晰易看
使用swagger生成的接口文档直观可视,脱离写接口文档的痛苦,及避免不厌其烦地解说各接口需要的参数和返回结果
2. 接口文档的查看简单易懂
接口路径查看
需要传递的参数查看
调用成功后返回的json数据有什么参数,参数的意思的什么的查看
3. 接口测试便利
接口测试,只需填好传参,然后点击Try it out!按钮即可
三、Swagger整合springMVC
1.依赖管理
&!-- swagger-springmvc --&
&&&&&dependency&
&&&&&&&&&groupId&com.mangofactory&/groupId&
&&&&&&&&&artifactId&swagger-springmvc&/artifactId&
&&&&&&&&&version&1.0.2&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.mangofactory&/groupId&
&&&&&&&&&artifactId&swagger-models&/artifactId&
&&&&&&&&&version&1.0.2&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.wordnik&/groupId&
&&&&&&&&&artifactId&swagger-annotations&/artifactId&
&&&&&&&&&version&1.3.11&/version&
&&&&&/dependency&
&&&&&!-- swagger-springmvc dependencies --&
&&&&&dependency&
&&&&&&&&&groupId&com.google.guava&/groupId&
&&&&&&&&&artifactId&guava&/artifactId&
&&&&&&&&&version&15.0&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.fasterxml.jackson.core&/groupId&
&&&&&&&&&artifactId&jackson-annotations&/artifactId&
&&&&&&&&&version&2.4.4&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.fasterxml.jackson.core&/groupId&
&&&&&&&&&artifactId&jackson-databind&/artifactId&
&&&&&&&&&version&2.4.4&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.fasterxml.jackson.core&/groupId&
&&&&&&&&&artifactId&jackson-core&/artifactId&
&&&&&&&&&version&2.4.4&/version&
&&&&&/dependency&
&&&&&dependency&
&&&&&&&&&groupId&com.fasterxml&/groupId&
&&&&&&&&&artifactId&classmate&/artifactId&
&&&&&&&&&version&1.1.0&/version&
&&&&&/dependency&
2.&Swagger配置
Swagger的配置实际上就是自定义一个Config类,通过java编码的方式实现配置。代码如下:
@Configuration
@EnableSwagger
public&class&SwaggerConfig {
private&SpringSwaggerConfig springSwaggerC
@Autowired
public&void&setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig&= springSwaggerC
&* Spring在启动的时候检测到@Bean的时候默认会在容器中注入一个以方法名(你的代码中是user)命名的Bean,而这个Bean用的是和该方法的返回类型一样的类(你的代码中是User)来初始化的。
public&SwaggerSpringMvcPlugin customImplementation(){
return&new&SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.enable(ConfigUtil.getInstance().getBoolean("enableSwagger"))//用于控制设置使用swagger
.includePatterns(".*?");
private&ApiInfo apiInfo(){
return&new&ApiInfo(ConfigUtil.getInstance().get("project.name"),"接口文档",null,ConfigUtil.getInstance().get("email"),null,null);
其中配置文件信息
#swagger 参数信息
enableSwagger=true
project.name=swagger
email=swagger@163.com
然后,将该配置交给spring管理,在springmvc的配置文件中加入以下配置
&bean&class="ssm.configer.SwaggerConfig "/&
或可通过扫描注入
自定义操作对象的接口方法
@Api(value="test-doc",description="用于测试")
@Controller
@RequestMapping("/test")
public&class&TestController {
@Autowired
private&CustomerService customerS
@RequestMapping(value="/get", method = RequestMethod.GET)
@ApiOperation(value="根据用户名获取对象",notes="获取对象")
public&@ResponseBody&CustomResult get(
@ApiParam("电话号码,必选") @RequestParam(value="phone",required=true)String phone) {
//Customer customer = customerService.findByPhone(phone);
Customer customer = new&Customer();
customer.setName("he");
return&CustomResult.ok(customer);
@RequestMapping(value="/find", method = RequestMethod.POST)
@ApiOperation(value="根据用户名获取对象",notes="获取对象")
@ApiResponses({
@ApiResponse(code=Constance.BASE_SUCCESS_CODE,message="成功",response=Customer.class),
@ApiResponse(code=Constance.BASE_FAIL_CODE,message="失败",response=String.class)
public&@ResponseBody&CustomResult find(
@ApiParam("电话号码,必选") @RequestParam(value="phone",required=true)String phone) {
//Customer customer = customerService.findByPhone(phone);
customer = new&Customer();
customer.setName("he");
} catch&(Exception e) {
// TODO&Auto-generated catch block
e.printStackTrace();
return&CustomResult.build(Constance.BASE_FAIL_CODE, Constance.map.get(Constance.BASE_FAIL_CODE));
return&CustomResult.ok(customer);
3. Swagger ui配置
从&获取其所有的 dist 目录下东西放到需要集成的项目里,本文放入 WebRoot/static/swagger/ 目录下。
修改swagger/index.html文件,并将其放在WebRoot下,如下
因为swagger-ui项目都是静态资源,restful形式的拦截方法会将静态资源进行拦截处理,所以在springmvc配置文件中需要配置对静态文件的处理方式。
&mvc:default-servlet-handler&&/mvc:default-servlet-handler&
打开浏览器直接访问项目下的index.html文件,即可看到接口文档说明了
四、Swagger的使用
整合好项目
然后就放进tomcat,启动
路径通常是:项目名+/api.html
这个就是写好的api,分别对应是以下这样
填好要传的参数,然后try it out按钮就能进行接口测试
客户端返回状态码
然后在Api接口添加这些
下面就是实体类的参数中文说明
阅读(...) 评论()spring boot - Springfox 404 Error When Testing API from Swagger UI - Stack Overflow
Join the Stack Overflow Community
Stack Overflow is a community of 7.1 million programmers, just like you, helping each other.
J it only takes a minute:
Investigating Springfox and Swagger UI, but I am facing an issue. I am using the Spring Boot REST example project as the foundation for my PoC. I'm running JDK 8 and the project leverages Gradle.
First, here are the file contents for the project:
build.gradle
buildscript {
repositories {
mavenCentral()
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.2.7.RELEASE")
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
baseName = 'gs-rest-service'
repositories {
mavenCentral()
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("io.springfox:springfox-swagger2:2.2.2")
compile("io.springfox:springfox-swagger-ui:2.2.2")
testCompile("junit:junit")
task wrapper(type: Wrapper) {
gradleVersion = '2.3'
GreetingController.java
import java.util.concurrent.atomic.AtomicL
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.bind.annotation.RequestP
import org.springframework.web.bind.annotation.RestC
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
Greeting.java
public class Greeting {
private final S
public Greeting(long id, String content) {
this.content =
public long getId() {
public String getContent() {
Application.java
import static mon.collect.Lists.newArrayL
import static springfox.documentation.schema.AlternateTypeRules.newR
import java.time.LocalD
import org.springframework.beans.factory.annotation.A
import org.springframework.boot.SpringA
import org.springframework.boot.autoconfigure.SpringBootA
import org.springframework.context.annotation.B
import org.springframework.http.ResponseE
import org.springframework.web.bind.annotation.RequestM
import org.springframework.web.context.request.async.DeferredR
import springfox.documentation.builders.PathS
import springfox.documentation.builders.RequestHandlerS
import springfox.documentation.builders.ResponseMessageB
import springfox.documentation.schema.ModelR
import springfox.documentation.schema.WildcardT
import springfox.documentation.spi.DocumentationT
import springfox.documentation.spring.web.plugins.D
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import com.fasterxml.classmate.TypeR
@SpringBootApplication
@EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
@Autowired
private TypeResolver typeR
public Docket greetingApi() {
return new Docket(DocumentationType.SPRING_WEB)
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.pathMapping("/")
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(newRule(typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder()
.code(500)
.message("500 message")
.responseModel(new ModelRef("Error"))
.build()))
.enableUrlTemplating(true);
Here is the issue I am facing. When I build and run the application, I can successfully navigate to the Swagger UI page (). When I expand greeting-controller, I see the different methods and expand "get /greeting{?name}". The Get section has the following content:
Response Class (Status 200)
"content": "string",
Response Content Type: */*
Parameters
parameter = name, value = World, parameter type = query, data type = string
When I click the "Try It Out" button, I see the following:
curl = curl -X GET --header "Accept: */*" "http://localhost:8080/greeting{?name}?name=World"
request url = http://localhost:8080/greeting{?name}?name=World
repsonse body = {
"timestamp": 9,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/greeting%7B"
response code = 404
response headers = {
"server": "Apache-Coyote/1.1",
"content-type": "application/charset=UTF-8",
"transfer-encoding": "chunked",
"date": "Sun, 01 Nov :46 GMT"
At first glance, it looks like for some reason that Springfox/Swagger is not correctly replacing the placeholder for {?name}. My question is, how do I configure it to do so, if that is in fact the issue, so that I can successfully test out the service from the Swagger UI page?
In your Application class changing the enableUrlTemplating to false will fix your problem.
public Docket greetingApi() {
return new Docket(DocumentationType.SPRING_WEB)
.enableUrlTemplating(false);
Just a little bit of background on that flag. That flag is to support
without which operations that differ only by query string parameters . In the next iteration of the swagger spec there are plans to address that issue. That is the reason for enableUrlTemplating to be marked as an .
2,08811633
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
rev .25989
Stack Overflow works best with JavaScript enabled