requests-rs icon indicating copy to clipboard operation
requests-rs copied to clipboard

Add Serde support

Open dtolnay opened this issue 9 years ago • 7 comments

If I know what the response body looks like, I want to be able to do something like:

#[derive(Deserialize)]
struct MyResponse {
    user: String,
    commits: Vec<Commit>,
}

fn main() {
    let resp: requests::Response = /* ... */;
    let body: MyResponse = resp.json().unwrap();
}

The implementation would look something like:

impl Response {
    /* ... */

    pub fn json<T>(&self) -> serde_json::Result<T> where T: Deserialize {
        serde_json::from_str(self.text().unwrap())
    }
}

dtolnay avatar Aug 20 '16 04:08 dtolnay

It used to be that way once - https://github.com/imp/requests-rs/commit/ed5e85abe98bf875d2a8647881d4be5c9ae09ee4#diff-6cfc163228cc31bed4a7214fa0b69300L66. May be it is time to re-introduce serde support back, as a feature. Let me play with it a bit.

imp avatar Aug 22 '16 09:08 imp

Thanks. For me the overwhelmingly common case is knowing what response I expect, so having to deal with an untyped JsonValue is bad. In the rare case that I don't know, I don't have a preference between json::JsonValue vs serde_json::Value.

dtolnay avatar Aug 22 '16 12:08 dtolnay

Serde's #[derive(Deserialize)] now works in the most recent stable compiler so this would be a good time to support it.

dtolnay avatar Feb 03 '17 04:02 dtolnay

@dtolnay Thanks for pinging me. serde support is under way in serde branch

imp avatar Feb 03 '17 07:02 imp

Nice! Let me know if you would like me to review the changes when you think the branch is ready.

dtolnay avatar Feb 03 '17 07:02 dtolnay

It looks like the current code on the serde branch is only using serde_json::Value which forfeits most of the advantages of Serde. I would like to be able to get back the response as any type T defined in my program.

let body: MyResponseType = resp.json().unwrap();

dtolnay avatar Feb 03 '17 07:02 dtolnay

Correct. And that is the reason I've said it is under way, rather that complete and ready to go :)

imp avatar Feb 03 '17 07:02 imp