REST API->传递json字符串作为参数值 [英] Rest API -> passing json string as parameter value
问题描述
是否建议在REST API中将JSON字符串作为参数值传递? 这是我要发送的数据:
Is it the recommended way to pass a JSON string as a parameter value in a REST API? This is the data which I am trying to send :
http://127.0.0.1:8000/v1/product/?productName= & metrics = {内存":2,"disk_space":10}
http://127.0.0.1:8000/v1/product/?productName=&metrics={"memory":2,"disk_space":10}
在这里,可以将指标的值作为JSON值传递吗?
Here, is it ok to pass the value of metrics as JSON value?
最初,我尝试在主体中传递指标JSON值.由于不支持/推荐标准,因此我将其删除.
Initially, I tried passing the metrics JSON value in the body. As it is not supported/recommended standard I have removed it.
推荐答案
是否建议在REST API中将JSON字符串作为参数值传递?
Is it the recommended way to pass a JSON string as a parameter value in a REST API?
REST是一种体系结构样式,它不执行(甚至定义)将JSON字符串作为参数值传递的任何标准.
REST is an architectural style and it doesn't enforce (or even define) any standards for passing JSON string as a parameter value.
如果要在查询字符串中发送JSON,则必须 URL编码首先:
If you want to send JSON in the query string, you must URL encode it first:
/v1/products?productName=&metrics=%7B%22memory%22%3A2%2C%22disk_space%22%3A10%7D
或者,您可以将参数重新设计为:
Alternativelly, you could redesign the parameters to be like:
/v1/products?productName=&metrics.memory=2&metrics.diskSpace=10
如果URL太长(或者查询变得太复杂而无法在查询字符串中表达),则可能需要考虑 GET
,然后在请求有效内容中发送JSON:
If the URL gets too long (or the query gets too complex to be expressed in the query string), you may want to consider POST
instead of GET
, and then send the JSON in the request payload:
POST /v1/products/search HTTP/1.1
Host: example.com
Content-Type: application/json
{
"productName": "foo",
"metrics": {
"memory": 2,
"diskSpace": 10
}
}
这篇关于REST API->传递json字符串作为参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!