Restful Api CRUD 标准示例 (Swagger2+validator)
为什么要写这篇贴?
要写一个最简单的CRUD 符合 Restful Api 规范的 一个Controller, 想百度搜索一下 直接复制拷贝 简单修改一下 方法内代码。
然而, 搜索结果让我无语到家。 没一个是正在符合 Restful Api 规范的实例。 最无语的是 你呀直接 JSP 页面了,还说什么 Restful Api 啊!!!
为方便以后自己复制拷贝使用,我把自己刚写的贴出来。
Swagger2:
@Configuration
@EnableSwagger2
public class Swagger2
{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dj.edi.web"))
.paths(PathSelectors.any())
.build();
} private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("EID 用户 CRUD")
.description("EID 用户 CRUD")
.version("1.0")
.build();
} }
Application:
@SpringBootApplication
@Import(springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class)
public class ComEdiOrderUserApplication
{
public static void main(String[] args) {SpringApplication.run(ComEdiOrderUserApplication.class, args);} }
UserApiController:
@RestController
@RequestMapping("/v1/user")
public class UserApiController
{
private static final Logger LOGGER = LoggerFactory.getLogger(UserApiController.class); @Autowired
private ClientUsersRepository repository; @ApiOperation(value = "获取所有用户数据")
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ResponseEntity<List<ClientUsers>> getClientUsersList() {
try {
return ResponseEntity.ok(repository.findAll());
} catch (Exception e) {
LOGGER.info(" 获取所有用户数据异常 " + e.getMessage(), e);
return ResponseEntity.status(500).body(null);
}
} @ApiOperation(value = "获取用户数据")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<ClientUsers> getClientUsers(@PathVariable String id) {
try {
return ResponseEntity.ok(repository.findOne(id));
} catch (Exception e) {
LOGGER.info(" 获取用户数据 " + id + " 数据异常 " + e.getMessage(), e);
return ResponseEntity.status(500).body(null);
}
} @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
@ApiImplicitParam(name = "users", value = "用户详细实体user", required = true, dataType = "ClientUsers", paramType = "body")
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<ClientUsers> createUser(@Valid @RequestBody ClientUsers users) {
try { users.setId(ObjectId.get().toString());
return ResponseEntity.ok(repository.save(users)); } catch (Exception e) {
LOGGER.info(" 创建用户 " + users + " 数据异常 " + e.getMessage(), e);
return ResponseEntity.status(500).body(null);
}
} @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "ClientUsers", paramType = "body")
})
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
public ResponseEntity<ClientUsers> updateUser(@PathVariable("id") String id,@Valid @RequestBody ClientUsers user) {
try {
user.setId(id);
return ResponseEntity.ok(repository.save(user));
} catch (Exception e) {
LOGGER.info(" 更新用户 " + user + " 数据异常 " + e.getMessage(), e);
return ResponseEntity.status(500).body(null);
}
} @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "path")
@RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteUser(@PathVariable String id) {
try {
repository.delete(id);
return ResponseEntity.ok("ok");
} catch (Exception e) {
LOGGER.info(" 删除用户 " + id + " 数据异常 " + e.getMessage(), e);
return ResponseEntity.status(500).body(null);
}
}
}
ClientUsersRepository:
@Component
public interface ClientUsersRepository extends MongoRepository<ClientUsers, String>
{
ClientUsers findByips(String ip);
ClientUsers findByclientFlag(String clientFlag);
}
ClientUsers:
@Data
public class ClientUsers implements Serializable
{ @Id
private String id; /**
* 用户名称
*/
@NotBlank(message = "用户名称 不能为空")
@Pattern(regexp = "^(?!string)",message = "不能是 stirng")
private String userName; /**
* ip
*/
@NotNull(message = "ip 至少需要个")
private List<String> ips; /**
* 标识
*/
@NotBlank(message = " 标识 不能为空")
@Pattern(regexp = "^(?!string)",message = "不能是 stirng")
private String clientFlag; /**
* 客户服务ID
*/
@NotBlank(message = "客户服务ID 不能为空")
@Pattern(regexp = "^(?!string)",message = "不能是 stirng")
private String checkID;
}
有哪里不好的希望指正
Restful Api CRUD 标准示例 (Swagger2+validator)的更多相关文章
- 虚拟研讨会:如何设计好的RESTful API?
http://www.infoq.com/cn/articles/how-to-design-a-good-restful-api/ REST架构风格最初由Roy T. Fielding(HTTP/1 ...
- 虚拟研讨会:如何设计好的RESTful API(转)
原文:虚拟研讨会:如何设计好的RESTful API? REST架构风格最初由Roy T. Fielding(HTTP/1.1协议专家组负责人)在其2000年的博士学位论文中提出.HTTP就是该架构风 ...
- 如何设计好的RESTful API 之好的RESTful API 特征
原文地址:http://blog.csdn.net/ywk253100/article/details/25654021 导读:设计好RESTful API对于软件架构的可扩展性.可伸缩性和消费者的体 ...
- 最好用的koa2+mysql的RESTful API脚手架,mvc架构,支持node调试,pm2部署。
#基于webpack构建的 Koa2 restful API 服务器脚手架 这是一个基于 Koa2 的轻量级 RESTful API Server 脚手架,支持 ES6, 支持使用TypeSc ...
- 我所理解的RESTful Web API [Web标准篇]
REST不是一个标准,而是一种软件应用架构风格.基于SOAP的Web服务采用RPC架构,如果说RPC是一种面向操作的架构风格,而REST则是一种面向资源的架构风格.REST是目前业界更为推崇的构建新一 ...
- SpringBoot使用Swagger2实现Restful API
很多时候,我们需要创建一个接口项目用来数据调转,其中不包含任何业务逻辑,比如我们公司.这时我们就需要实现一个具有Restful API的接口项目. 本文介绍springboot使用swagger2实现 ...
- 整合swagger2生成Restful Api接口文档
整合swagger2生成Restful Api接口文档 swagger Restful文档生成工具 2017-9-30 官方地址:https://swagger.io/docs/specificati ...
- Spring Boot中使用Swagger2生成RESTful API文档(转)
效果如下图所示: 添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!-- https://mvnrepository.com/artifact/io.springfox ...
- Swagger2在DBA Service中生成RESTful API的实践
目的与背景: 目的:对外暴露DBA Service必要的RESTful API,形成规整的API文档 背景:DBA Service后端采用Spring-boot,属于Spring家族,故生成API的工 ...
随机推荐
- mysql 创建函数ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_f
mysql 创建函数的时候 报错 ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQL D ...
- 并发编程 - 线程 - 1.线程queue/2.线程池进程池/3.异步调用与回调机制
1.线程queue :会有锁 q=queue.Queue(3) q.get() q.put() 先进先出 队列后进先出 堆栈优先级队列 """先进先出 队列"& ...
- Python3: Command not found(Mac OS)
1. 第一步:查看以下路径是否安装有 Python 3.x # 打开以下目录, 版本号有可能不同 cd /usr/local/Cellar/python/3.5.2_3/bin # 查看当前目录的内容 ...
- css冲突2 要关闭的css在项目代码以外,但是是通过<link>标签引入的css(例如bootstrap):解决方法,在APP.css中使用全局样式
css冲突,导致html字体过小. 通过浏览器检查发现,导致字体过小的css来自bootstrap. 现要关闭bootstrap的css: 直接在APP.css中添加: html{ font-size ...
- Python用MySQLdb, pymssql 模块通过sshtunnel连接远程数据库
转载自 https://www.cnblogs.com/luyingfeng/p/6386093.html 安全起见,数据库的访问多半是要做限制的,所以就有一个直接的问题是,往往多数时候,在别的机器上 ...
- springboot使用tomcat apr模式
因需项目对并发要求比较高.提高Tomcat效率.使用tomcat apr模式.今天在这记录下使用过程.apr全称为apache portable runtime.这里套用下wiki对apr的解释. T ...
- SDUT3145:Integer division 1(换零钱背包)
题目:传送门 题目描述 整数划分是一个非常经典的数学问题. 所谓整数划分,是指把一个正整数n写成为n=m1+m2+...+mi的形式,其中mi为正整数,并且1<=mi<=n,此时,{m1, ...
- Web UI 自动化单个xpath抓取插件详解
原文地址http://blog.csdn.net/kaka1121/article/details/51878346 单个控件获取 需求: 右键到某个控件上,就能获取到至多三个可以唯一定位该元素的相对 ...
- Delphi APP 開發入門(三)簡易計算機
Delphi APP 開發入門(三)簡易計算機 分享: Share on facebookShare on twitterShare on google_plusone_share 閲讀次數:68 ...
- Django:学习笔记(7)——模型进阶
Django:学习笔记(7)——模型进阶 模型的继承 我们在面向对象的编程中,一个很重要的的版块,就是类的继承.父类保存了所有子类共有的内容,子类通过继承它来减少冗余代码并进行灵活扩展. 在Djang ...