[英]REST API- use same URI & same method for different parameter to call different methods
I have a tricky situation where, I need to use same URI to call POST operation, one with single object & another with array of same type of objects. 我有一个棘手的情况,我需要使用相同的URI来调用POST操作,一个使用单个对象,另一个使用相同类型对象的数组。 Issue is I cant change URIs. 问题是我无法更改URI。 eg 例如
POST /my-services/v1/users with single user object as part of request body
& POST /my-services/v1/users with single user object as part of request body
&
POST /my-services/v1/users with array of user objects as part of request body
I cant change URI for 2nd operation eg /my-services/v1/ bulk -users 我无法为第二个操作更改URI,例如/ my-services / v1 / bulk -users
So, the question is, how to get such methods added in REST API? 因此,问题是,如何在REST API中添加此类方法?
In most JSON mappers (in example Jackson
) you can set a property ACCEPT_SINGLE_VALUE_AS_ARRAY
, Which will basically treat a single object as an array, so you can define your endpoints once (for collections). 在大多数JSON映射器(例如Jackson
)中,您可以设置属性ACCEPT_SINGLE_VALUE_AS_ARRAY
,该属性基本上会将单个对象视为数组,因此您可以一次定义端点(用于集合)。
Then you implement your endpoint as it always takes a Collection
as an input, and it will be handled by mapper even if a client will send single JSON object. 然后,您将实现端点,因为它始终将Collection
作为输入,并且即使客户端发送单个JSON对象,也将由mapper处理。
I would say add another param.
我会说添加另一个参数。
For example,
例如,
POST ... type=single&req=(user object)...
for the first one.
POST ... type=single&req=(user object)...
POST ... type=array&req=[user object]...
for the second one.
POST ... type=array&req=[user object]...
用于第二个。
The use switch case or if to check the type at the server.
使用开关盒或是否在服务器上检查类型。
Send the data and check the type at the server as Tim says. 如Tim所说,发送数据并在服务器上检查类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.