Java API 设计的关键最佳实践
来源:dev.to
时间:2024-11-01 21:49:04 376浏览 收藏
学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《Java API 设计的关键最佳实践》,以下内容主要包含等知识点,如果你正在学习或准备学习文章,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

介绍
对于专注于构建有效且可扩展的微服务的 java 开发人员来说,掌握 api 设计至关重要。本文概述了增强编码技能的最佳实践,并使用 java 示例来说明有效的技术与常见的错误。
1. 坚持restful原则
restful 架构依赖于无状态、可缓存性和统一接口等原则,促进一致的交互。
好示例:使用 post 请求创建新资源。
@restcontroller
@requestmapping("/products")
public class productcontroller {
@postmapping
public responseentity<product> createproduct(@requestbody product product) {
product savedproduct = productservice.save(product);
return responseentity.status(httpstatus.created).body(savedproduct);
}
}
避免示例:使用 delete 请求检索资源。
@restcontroller
@requestmapping("/products")
public class productcontroller {
@deletemapping("/{id}")
public responseentity<product> getproduct(@pathvariable long id) {
// incorrect; delete should not be used for retrieval.
product product = productservice.findbyid(id);
return responseentity.ok(product);
}
}
2. 使用适当的 http 状态代码
http 状态代码对于向客户端传达请求结果至关重要。
好示例:成功删除资源时返回 204 no content。
@deletemapping("/{id}")
public responseentity<void> deleteproduct(@pathvariable long id) {
productservice.deletebyid(id);
return responseentity.nocontent().build();
}
避免 示例:由于资源不存在而导致删除失败,返回 200 ok。
@deletemapping("/{id}")
public responseentity<void> deleteproduct(@pathvariable long id) {
if (!productservice.existsbyid(id)) {
return responseentity.ok().build(); // misleading response.
}
productservice.deletebyid(id);
return responseentity.nocontent().build();
}
3. 实施 api 版本控制
api 版本控制有助于在不中断现有用户的情况下管理变更,从而实现平稳过渡和更新。
好示例:为了清楚起见,在 uri 中使用版本。
@restcontroller
@requestmapping("/api/v2/orders")
public class ordercontroller {
// actions specific to version 2 of the orders api.
}
避免示例:没有版本控制,这可能会破坏客户端实现。
@restcontroller
@requestmapping("/orders")
public class ordercontroller {
// no versioning in place; risky for clients.
}
4. 优雅地处理异常
有效的错误处理通过提供有意义的错误消息来增强用户体验。
好示例:无效输入场景的自定义异常处理程序。
@exceptionhandler(invalidinputexception.class)
public responseentity<string> handleinvalidinput(invalidinputexception ex) {
return responseentity.badrequest().body(ex.getmessage());
}
避免示例:返回缺乏详细信息的通用错误消息。
@exceptionhandler(exception.class)
public responseentity<string> handleallerrors(exception ex) {
// bad practice; vague error message is unhelpful.
return responseentity.status(httpstatus.internal_server_error).body("error occurred");
}
5. api 设计中优先考虑安全性
安全至关重要; api 应强制执行身份验证和授权以保护敏感数据。
好示例:在访问资源之前检查用户权限。
@getmapping("/orders/{id}")
public responseentity<order> getorderbyid(@pathvariable long id) {
if (!authservice.haspermission("view_order", id)) {
return responseentity.status(httpstatus.forbidden).build();
}
order order = orderservice.findbyid(id);
return order != null ? responseentity.ok(order) : responseentity.notfound().build();
}
避免示例:忽视授权检查,面临未经授权访问的风险。
@getmapping("/orders/{id}")
public responseentity<order> getorderbyid(@pathvariable long id) {
// missing permission check; poses a security risk.
order order = orderservice.findbyid(id);
return responseentity.ok(order);
}
6. 维护清晰的 api 文档
完整的文档可以帮助开发人员了解如何有效地使用 api,从而促进集成的简便性。
好示例:使用 openapi 注释来获得清晰的文档。
@api(tags = "order management")
@restcontroller
@requestmapping("/api/v1/orders")
public class ordercontroller {
// actions documented with openapi annotations.
}
避免示例:缺乏文档,导致 api 难以导航。
@restcontroller
@requestmapping("/orders")
public class ordercontroller {
// actions without any documentation or comments.
}
7. 明智地使用查询参数
查询参数允许客户端对结果进行过滤、排序和分页,从而增强灵活性。
好示例:支持分页和过滤的端点。
@getmapping("/products")
public responseentity<list<product>> getproducts(
@requestparam optional<string> category,
@requestparam(defaultvalue = "0") int page,
@requestparam(defaultvalue = "10") int size) {
list<product> products = productservice.findproducts(category, page, size);
return responseentity.ok(products);
}
避免示例:返回大型数据集而不进行任何过滤或分页。
@getmapping("/products")
public responseentity<list<product>> getallproducts() {
return responseentity.ok(productservice.findall()); // excessive data returned.
}
8. 实施 http 缓存策略
缓存通过最小化服务器负载和响应时间来提高性能。
好示例:使用缓存控制标头来优化响应。
@getmapping("/products/{id}")
public responseentity<product> getproductbyid(@pathvariable long id) {
product product = productservice.findbyid(id);
return responseentity.ok()
.cachecontrol(cachecontrol.maxage(30, timeunit.seconds))
.body(product);
}
避免示例:未能利用缓存标头,导致冗余数据传输。
@getmapping("/products/{id}")
public responseentity<product> getproductbyid(@pathvariable long id) {
return responseentity.ok(productservice.findbyid(id)); // no caching utilized.
}
9. 确保直观的 api 设计
api 应该简单、自描述,并具有逻辑命名约定。
好示例:使用清晰且描述性的端点名称。
@postmapping("/users")
public responseentity<user> registeruser(@requestbody user user) {
// clearly indicates user registration.
}
@getmapping("/users/{id}")
public responseentity<user> fetchuserbyid(@pathvariable long id) {
// clearly indicates fetching a user by id.
}
避免示例:令人困惑的端点路径掩盖了其目的。
@putmapping("/updateuserinfo")
public responseentity<user> updateuser(@requestbody user user) {
// unclear path; doesn't specify the resource being updated.
}
10.启用响应压缩
通过响应压缩优化有效负载大小可提高性能。
好示例:配置服务器以启用 gzip 压缩。
propertiescopy code# in spring boot application.properties server.compression.enabled=true server.compression.mime-types=application/json,text/html
避免示例:发送大响应而不压缩,增加加载时间。
@getmapping("/products")
public responseentity<list<product>> getallproducts() {
return responseentity.ok(productservice.findall()); // large payload without compression.
}
11.拥抱异步处理
异步操作对于管理长时间运行的任务而不阻塞客户端至关重要。
很好示例:使用异步处理处理批量请求。
@postmapping("/orders/batch")
public responseentity<void> batchcreateorders(@requestbody list<order> orders) {
completablefuture<void> future = orderservice.createordersasync(orders);
httpheaders headers = new httpheaders();
headers.setlocation(uri.create("/orders/batch/status"));
return responseentity.accepted().headers(headers).build();
}
避免示例:同步处理使客户端等待长时间操作。
@PostMapping("/orders/batch")
public ResponseEntity<List<Order>> batchCreateOrders(@RequestBody List<Order> orders) {
List<Order> createdOrders = orderService.createOrders(orders); // This could block.
return ResponseEntity.ok(createdOrders);
}
结论
通过应用这些最佳实践,开发人员可以创建健壮、可维护且用户友好的 api。这种方法不仅有助于构建高质量的 api,还确保它们可以随着时间的推移而发展,而不会对客户造成干扰。
参考
- restful web api 设计
- gitlab api 设计指南
- rest 架构约束
- 标准响应状态代码
- api 风格指南
- 学习 rest api 设计
理论要掌握,实操不能落!以上关于《Java API 设计的关键最佳实践》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
164 收藏
-
341 收藏
-
125 收藏
-
427 收藏
-
152 收藏
-
129 收藏
-
334 收藏
-
431 收藏
-
294 收藏
-
292 收藏
-
183 收藏
-
288 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习