简体   繁体   English

单一 API 端点的优缺点

[英]Single API endpoint pros and cons

I am creating API and trying to figure out is planned approach any good.我正在创建 API 并试图找出计划好的方法。
That API is not public and it will be used by SPA and mobile app that I build.该 API 不是公开的,它将被我构建的 SPA 和移动应用程序使用。
So I am thinking of GraphQL-like design but without posting json and with regular HTTP methods.所以我在考虑类似 GraphQL 的设计,但没有发布 json 和常规的 HTTP 方法。 Something like this for GET methods:对于 GET 方法,类似这样的事情:

Example 1 - get users with specific fields(_join indicates sql table join), ordering and limit:示例 1 - 获取具有特定字段的用户(_join 表示 sql table join),排序和限制:
api.com?table=users&displayFields=id,name,email,address,tel,country_join&orderBy=asc&orderColumn=name&offset=0&limit=10

Example 2 - get users based on search parameters with all fields, ordering and limit:示例 2 - 基于所有字段、排序和限制的搜索参数获取用户:
api.com?table=users&search=John&searchFields=name,email&orderBy=asc&orderColumn=name&offset=0&limit=10

I assume this is bad since REST is standard, otherwise I would see much more examples of this approach.我认为这很糟糕,因为 REST 是标准的,否则我会看到更多这种方法的例子。
But why is this bad?但为什么这很糟糕? For me it seems easier to develop and more flexible to use.对我来说,它似乎更容易开发和使用更灵活。
Is proper REST API for examples I provided easier to implement, safer, easier to use or cache?我提供的示例的适当 REST API 是否更易于实现、更安全、更易于使用或缓存?

The main difference I see between putting the variables in the url vs the request body are:我看到将变量放入 url 与请求正文之间的主要区别是:

  • the length of the data as the url length is limited while the request body is not数据的长度作为 url 长度是有限的,而请求体不是
  • special characters to be escaped in the url which can lead to long and unclear url要在 url 中转义的特殊字符,这可能导致 url 长而不清楚

These are 2 pros in favor of data in request body, but I agree that data in url is much simpler to test and use as tou don't need an http client tool like curl or postman to validate your endpoints.这是支持请求正文中数据的 2 个优点,但我同意 url 中的数据更易于测试和使用,因为您不需要像 curl 或邮递员这样的 http 客户端工具来验证您的端点。

REST however has stricter conventions if you want to fully implement it:然而,如果你想完全实现它,REST 有更严格的约定:

  • use the right http requests (get, post, patch, delete and put) to implement crud operations on one single endpoint使用正确的 http 请求(get、post、patch、delete 和 put)在单个端点上实现 crud 操作
  • return the right http code as a result结果返回正确的http代码
  • use standard data format for input and output (json or XML)使用标准数据格式进行输入和输出(json 或 XML)

For better interoperability between systems it's advised to comply with REST and microservices design patterns.为了更好地实现系统之间的互操作性,建议遵守 REST 和微服务设计模式。

For small applications we can follow some shortcuts and not comply fully.对于小型应用程序,我们可以遵循一些捷径而不完全遵守。 I have integrated several services so far and each time I can tell you no one of them implements standard REST :-)到目前为止,我已经集成了几个服务,每次我都可以告诉你,没有一个服务实现了标准的 REST :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM