Skip to content

Commit 863c4a6

Browse files
committed
Switch from json to urlencoded for POST body
1 parent ba2c5f1 commit 863c4a6

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

src/client.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ impl Client<'_> {
8181
.client
8282
.post(format!("{}/{}", self.api.url(), endpoint))
8383
.header("Content-Type", "application/x-www-form-urlencoded")
84-
.body(serde_json::to_string(&parameters)?); // TODO: switch to URL encoding
84+
.body(Self::urlencoded_from_json(parameters));
8585

8686
Ok(self.request(request).await?)
8787
}
@@ -97,4 +97,40 @@ impl Client<'_> {
9797
.json()
9898
.await?)
9999
}
100+
101+
fn urlencoded_from_json(json: &Value) -> String {
102+
if let Some(v) = json.as_object() {
103+
v.iter()
104+
.map(|(key, value)| {
105+
format!(
106+
"{}={}",
107+
key,
108+
match value {
109+
Value::String(s) => s.to_owned(), // serde_json String(_) formatter includes the quotations marks, this doesn't
110+
_ => format!("{}", value),
111+
}
112+
)
113+
})
114+
.collect::<Vec<String>>()
115+
.join("&")
116+
} else {
117+
String::new()
118+
}
119+
}
120+
}
121+
122+
#[cfg(test)]
123+
mod tests {
124+
use serde_json::json;
125+
#[test]
126+
fn urlencoded_from_json() {
127+
assert_eq!(
128+
super::Client::urlencoded_from_json(&json!({
129+
"a": 1,
130+
"b": true,
131+
"c": "test_string"
132+
})),
133+
"a=1&b=true&c=test_string"
134+
);
135+
}
100136
}

0 commit comments

Comments
 (0)