Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the Json extractor with the 2.1 Rust template #23

Open
itowlson opened this issue Dec 14, 2023 · 2 comments
Open

Using the Json extractor with the 2.1 Rust template #23

itowlson opened this issue Dec 14, 2023 · 2 comments

Comments

@itowlson
Copy link
Contributor

In Spin 2.0.1, the Rust template referenced the http crate, and we supported the Json<T> extractor as a body type parameter e,g, http::Request<Json<Person>>.

In Spin 2.1, the Rust template does not reference the http crate and users are directed instead to the spin_sdk::http::Request type. This type is not generic - the body is always presented as bytes - and we do not have seem to have samples of how to use the extractors with it. I guess you can do something like Jsion::<Person>::try_from_body(req.into_body()) but it's not as friendly as the extractor syntax!

If the extractors work with the SDK request type, it would be good to provide samples that show how; if they don't, we should provide that functionality.

@rylev
Copy link
Contributor

rylev commented Dec 15, 2023

The following used to work in the run up to 2.0 but was removed because of some fears that it was potentially confusing:

use std::collections::HashMap;
use spin_sdk::{http::{Json, Response}, http_component};

/// A simple Spin HTTP component.
#[http_component]
fn handle(body: Json<HashMap<String, String>>) -> Response {
    println!("Incoming Body: {body:#?}");
    Response::new(200, Vec::new())
}

We could make this work again if we want, but of course, the user then doesn't have access to any other parts of the request.

Alternatively, we could add a json method to Request that allows users to access the body in some deserialized form.

@itowlson
Copy link
Contributor Author

A json method feels very specific (although admittedly the "80% case" kind of specific, with String and maybe form-encoded being the other biggies). I had also wondered about a function called something like into_body_as() or extract, but the req.extract::<Json<Person>>() syntax is a bit spiky.

Another, although maybe hairy, possibility is a typed form of request e.g. spin_sdk::http::typed::Request<T>. It could be a testing and maintenance pain though, and of course a discoverability issue and extra cognitive load for users.

@vdice vdice transferred this issue from fermyon/spin Mar 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: 📋 Investigating / Open for Comment
Development

No branches or pull requests

2 participants