[JavaEE] Create API documents with Swagger
We mainly need to modify our Model and REST endpoint code to enable swagger Document.
model/Book.java: By doing this, we can get each model defination in swagger
rest/BookRespostory.java: By doing this, we can get each endpoint of API
BoodEndpoint.java:
package com.pluralsight.bookstore.rest; import com.pluralsight.bookstore.model.Book;
import com.pluralsight.bookstore.repository.BookRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN; @Path("/books")
@Api("Book")
public class BookEndpoint { // ======================================
// = Injection Points =
// ====================================== @Inject
private BookRepository bookRepository; // ======================================
// = Business methods =
// ====================================== @POST
@Consumes(APPLICATION_JSON)
@ApiOperation(value = "Create a book given a Json Book reforestation")
@ApiResponses({
@ApiResponse(code = 201, message = "The book was created"),
@ApiResponse(code = 415, message = "Format error")
})
public Response createBook(Book book, @Context UriInfo uriInfo) {
book = bookRepository.create(book);
URI createdURI = uriInfo.getBaseUriBuilder().path(book.getId().toString()).build();
return Response.created(createdURI).build();
} @GET
@Path("/{id : \\d+}")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Returns a book given an id", response = Book.class)
@ApiResponses({
@ApiResponse(code = 200, message = "Book found"),
@ApiResponse(code = 404, message = "Book not found")
})
public Response getBook(@PathParam("id") @Min(1) Long id) {
Book book = bookRepository.find(id); if (book == null)
return Response.status(Response.Status.NOT_FOUND).build(); return Response.ok(book).build();
} @DELETE
@Path("/{id : \\d+}")
@ApiOperation(value = "Delete a book given an id")
@ApiResponses({
@ApiResponse(code = 204, message = "Book has been deleted"),
@ApiResponse(code = 400, message = "Invalid param id"),
@ApiResponse(code = 500, message = "Book not exists")
})
public Response deleteBook(@PathParam("id") @Min(1) Long id) {
bookRepository.delete(id);
return Response.noContent().build();
} }
model/Book.java:
package com.pluralsight.bookstore.model; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import javax.persistence.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import java.util.Date; /**
* @author Antonio Goncalves
* http://www.antoniogoncalves.org
* --
*/ @Entity
@ApiModel(description = "Book resource representation")
public class Book { // ======================================
// = Attributes =
// ====================================== @Id
@GeneratedValue
@ApiModelProperty("Identifier")
private Long id; @Column(length = 200)
@NotNull
@Size(min = 1, max = 200)
@ApiModelProperty("Title of the book")
private String title; @Column(length = 10000)
@Size(min = 1, max = 10000)
@ApiModelProperty("Description of the book")
private String description; // ======================================
// = Constructors =
// ====================================== public Book() {
} public Book(String isbn, String title, Float unitCost, Integer nbOfPages, com.pluralsight.bookstore.model.Language language, Date publicationDate, String imageURL, String description) {
this.isbn = isbn;
this.title = title;
this.unitCost = unitCost;
this.nbOfPages = nbOfPages;
this.language = language;
this.publicationDate = publicationDate;
this.imageURL = imageURL;
this.description = description;
} }
In the end, the Swagger.json looks like this:
{
"swagger" : "2.0",
"info" : {
"description" : "BookStore APIs exposed from a Java EE back-end to an Angular front-end",
"version" : "1.0.0",
"title" : "BookStore APIs",
"contact" : {
"name" : "Antonio Goncalves",
"url" : "https://app.pluralsight.com/library/search?q=Antonio+Goncalves",
"email" : "antonio.goncalves@gmail.com"
}
},
"host" : "localhost:8080",
"basePath" : "/bookstore-back/api",
"tags" : [ {
"name" : "Book"
} ],
"schemes" : [ "http", "https" ],
"paths" : {
"/books" : {
"get" : {
"tags" : [ "Book" ],
"summary" : "Returns all the books",
"description" : "",
"operationId" : "getBooks",
"produces" : [ "application/json" ],
"responses" : {
"200" : {
"description" : "Books found",
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/definitions/Book"
}
}
},
"204" : {
"description" : "No books found"
}
}
},
"post" : {
"tags" : [ "Book" ],
"summary" : "Creates a book given a JSon Book representation",
"description" : "",
"operationId" : "createBook",
"consumes" : [ "application/json" ],
"parameters" : [ {
"in" : "body",
"name" : "body",
"description" : "Book to be created",
"required" : true,
"schema" : {
"$ref" : "#/definitions/Book"
}
} ],
"responses" : {
"201" : {
"description" : "The book is created"
},
"415" : {
"description" : "Format is not JSon"
}
}
}
},
"/books/count" : {
"get" : {
"tags" : [ "Book" ],
"summary" : "Returns the number of books",
"description" : "",
"operationId" : "countBooks",
"produces" : [ "text/plain" ],
"responses" : {
"200" : {
"description" : "Number of books found",
"schema" : {
"type" : "integer",
"format" : "int64"
}
},
"204" : {
"description" : "No books found"
}
}
}
},
"/books/{id}" : {
"get" : {
"tags" : [ "Book" ],
"summary" : "Returns a book given an id",
"description" : "",
"operationId" : "getBook",
"produces" : [ "application/json" ],
"parameters" : [ {
"name" : "id",
"in" : "path",
"required" : true,
"type" : "integer",
"minimum" : 1.0,
"pattern" : "\\d+",
"format" : "int64"
} ],
"responses" : {
"200" : {
"description" : "Book found",
"schema" : {
"$ref" : "#/definitions/Book"
}
},
"400" : {
"description" : "Invalid input. Id cannot be lower than 1"
},
"404" : {
"description" : "Book not found"
}
}
},
"delete" : {
"tags" : [ "Book" ],
"summary" : "Deletes a book given an id",
"description" : "",
"operationId" : "deleteBook",
"parameters" : [ {
"name" : "id",
"in" : "path",
"required" : true,
"type" : "integer",
"minimum" : 1.0,
"pattern" : "\\d+",
"format" : "int64"
} ],
"responses" : {
"204" : {
"description" : "Book has been deleted"
},
"400" : {
"description" : "Invalid input. Id cannot be lower than 1"
},
"500" : {
"description" : "Book not found"
}
}
}
}
},
"definitions" : {
"Book" : {
"type" : "object",
"required" : [ "isbn", "title" ],
"properties" : {
"id" : {
"type" : "integer",
"format" : "int64",
"description" : "Identifier"
},
"title" : {
"type" : "string",
"description" : "Title of the book",
"minLength" : 1,
"maxLength" : 200
},
"description" : {
"type" : "string",
"description" : "Summary describing the book",
"minLength" : 1,
"maxLength" : 10000
},
"unitCost" : {
"type" : "number",
"format" : "float",
"description" : "Unit cost",
"minimum" : 1.0
},
"isbn" : {
"type" : "string",
"description" : "ISBN number",
"minLength" : 1,
"maxLength" : 50
},
"publicationDate" : {
"type" : "string",
"format" : "date-time",
"description" : "Date in which the book has been published"
},
"nbOfPages" : {
"type" : "integer",
"format" : "int32",
"description" : "Number of pages"
},
"imageURL" : {
"type" : "string",
"description" : "URL of the image cover"
},
"language" : {
"type" : "string",
"description" : "Language in which the book has been written",
"enum" : [ "ENGLISH", "FRENCH", "SPANISH", "PORTUGUESE", "ITALIAN", "FINISH", "GERMAN", "DEUTSCH", "RUSSIAN" ]
}
},
"description" : "Book resource representation"
}
}
}
[JavaEE] Create API documents with Swagger的更多相关文章
- 在ASP.NET Core Web API上使用Swagger提供API文档
我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...
- Core Web API上使用Swagger提供API文档
在ASP.NET Core Web API上使用Swagger提供API文档 我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的AP ...
- ASP.NET Core Web API中使用Swagger
本节导航 Swagger介绍 在ASP.NET CORE 中的使用swagger 在软件开发中,管理和测试API是一件重要而富有挑战性的工作.在我之前的文章<研发团队,请管好你的API文档& ...
- JAVAEE 7 api.chm
JAVAEE 7 api.chm 链接:https://pan.baidu.com/s/1LUD3oam5B-Hp8tdpfQYk2w 提取码:x1kc
- 2种方式解决nginx负载下的Web API站点里swagger无法使用
Web API接口站点,引入了swagger来实时生成在线的api文档,也便于api接口的在线测试.swagger:The World's Most Popular Framework for API ...
- gRPC helloworld service, RESTful JSON API gateway and swagger UI
概述 本篇博文完整讲述了如果通过 protocol buffers 定义并启动一个 gRPC 服务,然后在 gRPC 服务上提供一个 RESTful JSON API 的反向代理 gateway,最后 ...
- WebApi生成在线API文档--Swagger
1.前言 1.1 SwaggerUI SwaggerUI 是一个简单的Restful API 测试和文档工具.简单.漂亮.易用(官方demo).通过读取JSON 配置显示API. 项目本身仅仅也只依赖 ...
- ASP.NET Web API 中使用 swagger 来管理 API 文档
本文以 ASP.NET Web API 为后台框架,利用 EF6 连接 postgreSQL 数据库,使用 swagger 来生成 REST APIs文档.文章分二个部分,第一部分主要讲如何用 EF6 ...
- Asp.Net Web Api中使用Swagger
关于swagger 设计是API开发的基础.Swagger使API设计变得轻而易举,为开发人员.架构师和产品所有者提供了易于使用的工具. 官方网址:https://swagger.io/solutio ...
随机推荐
- 生成清除某个数据库下的所有表的SQL语句
方法1:重建库和表 用mysqldump --no-data把建表SQL导出来,然后drop database再create database,执行一下导出的SQL文件: 方法2:生成清空所有表的SQ ...
- SQL数据库——静态成员
静态: 1.普通成员普通成员都是属于对象的用对象调用 2.静态成员静态成员是属于类的用类名调用 stactic 静态关键字 静态方法里面不能包含普通成员普通方法里面可以包含静态成员 静态: 1.普通成 ...
- 什么是2MSL以及TIME_WAIT的作用
TIME_WAIT主要是用来解决以下几个问题: 1)上面解释为什么主动关闭方需要进入TIME_WAIT状态中提到的: 主动关闭方需要进入TIME_WAIT以便能够重发丢掉的被动关闭方FIN包的ACK. ...
- ajax怎么理解?
Ajix是创建交互式网页的前端网页开发技术,不是一种语言,ajax是基于http来传输数据的,他是利用浏览器提供操作http的接口(XMLHttpRequest或者activeXobject),来操作 ...
- mvc使用linq to sql进行sum统计遇到查询为null的问题
mvc linq to sql,linq to entity,sum,null 昨天写了段sum的统计语句, decimal sums sums = ( from fac in db.Apply wh ...
- url-safe base64 && base64
1: 为什么需要base64? ASCII码一共规定了128个字符的编码,这128个符号,范围在[0,127]之间. 其中,[0,31],及127, 33个属于不可打印的控制字符. 在电子邮件传输信息 ...
- HDU_3172_带权并查集
Virtual Friends Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)T ...
- JAVA基础——IO流字节流
在Java中把不同的输入输出源(键盘.文件.网路连接)抽象表述为“流”. 1.输入流.输出流 .字节输入流通过FileInputStream和来操作 字节输出流通过FileOutputStream来操 ...
- 数据结构与算法(3)- C++ STL与java se中的vector
声明:虽然本系列博客与具体的编程语言无关.但是本文作者对c++相对比较熟悉,其次是java,所以难免会有视角上的偏差.举例也大多是和这两门语言相关. 上一篇博客概念性的介绍了vector,我们有了大致 ...
- form表单传输多余参数
1.使用post提交表单,同时在form的action属性后添加“?参数=参数值”,经验证,可行,但是在浏览器中看不到该参数在form参数中,如下图: 上图未出现courseId属性,form代码如下 ...