简体   繁体   English

RESTful API设计:内部交互

[英]RESTful API design: inner interaction

Simple question. 简单的问题。 I read a bunch of articles about API design and didn't find the answer. 我读了很多关于API设计的文章,但没有找到答案。

How should API's endpoints interact with each other? API的端点应如何相互交互?

For example, if I have 2 endpoints: /category/:name and /messages . 例如,如果我有2个端点: /category/:name/messages What is the best way for example to check category existence from messages? 例如,从消息中检查类别是否存在的最佳方法是什么?

1) Database query from /messages handler like: SELECT * FROM categories WHERE name = 'test'? 1)从/messages处理程序进行数据库查询,例如:SELECT * FROM category WHERE name ='test'

or 要么

2) HTTP request from /messages handler to that endpoint like: httpclient.get('/category/test') ? 2)从/messages处理程序到该端点的HTTP请求,例如:httpclient.get('/ category / test')?

or 要么

3) Client should get all categories, get ID of particular category and send request to /messages with that category ID? 3)客户应该获取所有类别,获取特定类别的ID,然后使用该类别ID向/messages发送请求?

The question is simple but not an answer. 问题很简单,但不是答案。 One thing is sure, never use (2) solution. 可以肯定的是,永远不要使用(2)解决方案。 Requesting some data using http client when you can invoke a method will decrease performance and capacity of your API. 当您可以调用方法时,使用http客户端请求一些数据将降低API的性能和容量。

If checking existence of a particular category is required to create response in /messages then use (1) but instead of invoking SQL query invoke the same method as used to handle request to /category/test just invoke it locally not through HTTP. 如果需要检查是否存在特定类别才能在/messages创建响应,请使用(1),而不是调用SQL查询来调用与处理/category/test请求相同的方法,而不必通过HTTP在本地进行调用。

Solution (3) is the REST-way when each endpoint is responsible only for one type of resources. 当每个端点仅负责一种类型的资源时,解决方案(3)是REST方式。 The disadvantage is that it may require more HTTP requests from client to API. 缺点是可能需要从客户端到API的更多HTTP请求。

You should design your application in a way that all the endpoint are calling internal APIs for performing the task. 您应该以所有端点都调用内部API来执行任务的方式设计应用程序。 When you want to invoke one operation inside other then you should use the respective internal API instead of any other approach like calling http service. 当您想在其他内部调用一个操作时,则应使用各自的内部API,而不要使用其他任何方法(如调用http服务)。

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

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