当前位置:首页 > 文章列表 > 文章 > 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<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学习网公众号吧!

版本声明
本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
网页元素排版与 HTML 内容不一致,该如何排查问题? 
网页元素排版与 HTML 内容不一致,该如何排查问题?
上一篇
网页元素排版与 HTML 内容不一致,该如何排查问题?
使用 Vue CLI 引入本地 JavaScript 文件出现 \
下一篇
使用 Vue CLI 引入本地 JavaScript 文件出现 \"Uncaught SyntaxError: Unexpected token \'
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    542次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    511次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    498次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    484次学习
查看更多
AI推荐
  • 千音漫语:智能声音创作助手,AI配音、音视频翻译一站搞定!
    千音漫语
    千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
    245次使用
  • MiniWork:智能高效AI工具平台,一站式工作学习效率解决方案
    MiniWork
    MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
    239次使用
  • NoCode (nocode.cn):零代码构建应用、网站、管理系统,降低开发门槛
    NoCode
    NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
    235次使用
  • 达医智影:阿里巴巴达摩院医疗AI影像早筛平台,CT一扫多筛癌症急慢病
    达医智影
    达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
    245次使用
  • 智慧芽Eureka:更懂技术创新的AI Agent平台,助力研发效率飞跃
    智慧芽Eureka
    智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
    266次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码