当前位置:首页 > 文章列表 > 文章 > java教程 > Java API 设计的关键最佳实践

Java API 设计的关键最佳实践

来源:dev.to 2024-11-01 21:49:04 0浏览 收藏

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

Java API 设计的关键最佳实践

介绍

对于专注于构建有效且可扩展的微服务的 java 开发人员来说,掌握 api 设计至关重要。本文概述了增强编码技能的最佳实践,并使用 java 示例来说明有效的技术与常见的错误。

1. 坚持restful原则

restful 架构依赖于无状态、可缓存性和统一接口等原则,促进一致的交互。

好示例:使用 post 请求创建新资源。

@restcontroller
@requestmapping("/products")
public class productcontroller {

    @postmapping
    public responseentity 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 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 deleteproduct(@pathvariable long id) {
    productservice.deletebyid(id);
    return responseentity.nocontent().build();
}

避免 示例:由于资源不存在而导致删除失败,返回 200 ok。

@deletemapping("/{id}")
public responseentity 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 handleinvalidinput(invalidinputexception ex) {
    return responseentity.badrequest().body(ex.getmessage());
}

避免示例:返回缺乏详细信息的通用错误消息。

@exceptionhandler(exception.class)
public responseentity 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 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 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> getproducts(
        @requestparam optional category,
        @requestparam(defaultvalue = "0") int page,
        @requestparam(defaultvalue = "10") int size) {
    list products = productservice.findproducts(category, page, size);
    return responseentity.ok(products);
}

避免示例:返回大型数据集而不进行任何过滤或分页。

@getmapping("/products")
public responseentity> getallproducts() {
    return responseentity.ok(productservice.findall()); // excessive data returned.
}

8. 实施 http 缓存策略

缓存通过最小化服务器负载和响应时间来提高性能。

好示例:使用缓存控制标头来优化响应。

@getmapping("/products/{id}")
public responseentity 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 getproductbyid(@pathvariable long id) {
    return responseentity.ok(productservice.findbyid(id)); // no caching utilized.
}

9. 确保直观的 api 设计

api 应该简单、自描述,并具有逻辑命名约定。

好示例:使用清晰且描述性的端点名称。

@postmapping("/users")
public responseentity registeruser(@requestbody user user) {
    // clearly indicates user registration.
}

@getmapping("/users/{id}")
public responseentity fetchuserbyid(@pathvariable long id) {
    // clearly indicates fetching a user by id.
}

避免示例:令人困惑的端点路径掩盖了其目的。

@putmapping("/updateuserinfo")
public responseentity 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> getallproducts() {
    return responseentity.ok(productservice.findall()); // large payload without compression.
}

11.拥抱异步处理

异步操作对于管理长时间运行的任务而不阻塞客户端至关重要。

很好示例:使用异步处理处理批量请求。

@postmapping("/orders/batch")
public responseentity batchcreateorders(@requestbody list orders) {
    completablefuture 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> batchCreateOrders(@RequestBody List orders) {
    List 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学习网公众号吧!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
网页元素排版与 HTML 内容不一致,该如何排查问题? 
网页元素排版与 HTML 内容不一致,该如何排查问题?
上一篇
网页元素排版与 HTML 内容不一致,该如何排查问题?
使用 Vue CLI 引入本地 JavaScript 文件出现 \
下一篇
使用 Vue CLI 引入本地 JavaScript 文件出现 \"Uncaught SyntaxError: Unexpected token \'
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • PubMedQA数据集详解:生物医学问答基准、功能与应用指南
    PubMedQA
    深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
    1130次使用
  • H2O EvalGPT:开源LLM大模型评估与排行榜工具
    H2O EvalGPT
    H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
    1114次使用
  • LMArena是什么?伯克利AI模型评估平台使用指南与功能解析
    LMArena
    LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
    1289次使用
  • 斯坦福HELM:大语言模型Holistic Evaluation整体评估框架详解
    HELM
    深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
    1228次使用
  • MMBench详解:多模态大模型基准测试、功能特点与使用指南
    MMBench
    MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
    1079次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议 和 隐私政策
返回登录
  • 重置密码