Rust warp How to proxy request with json payload to another url by adding extra header?

1.2k views Asked by At

How to add extra header like access_token : jshaj_some_really_long_token and also set content-type to Content-Type: application/json in warp post call?

Scenario in detail:

  1. I want to create API using warp say the end point is https://example.com/orders
  2. The type is post which needs a payload => '{ "myid" : 12 , "price" : 23.2, "transaction" : "buy", "quantity" : 10 }'
  3. Now I want to use reqwest or any in built warp http client to send a request to another server endpoint say https://api.example.com/orders with the above post payload but with the new header which is Content-Type: application/json and access-token: jshaj_some_really_long_token

Please do share if there are some examples which are using warp and reqwest for post requests. Currently I am referring this

1

There are 1 answers

3
Netwave On

You can use the warp-reverse-proxy crate for that (maintainer here :) )

You would have to compose the utilities inside to modify what you need as per the example:

#[tokio::main]
async fn main() {
    let hello = warp::path!("hello" / String).map(|name| format!("Hello port, {}!", name));

    // // spawn base server
    tokio::spawn(warp::serve(hello).run(([0, 0, 0, 0], 8080)));

    let request_filter = extract_request_data_filter();
    let app = warp::path!("hello" / String)
        // build proxy address and base path data from current filter
        .map(|port| (format!("http://127.0.0.1:{}/", port), "".to_string()))
        .untuple_one()
        // build the request with data from previous filters
        .and(request_filter)
        .and_then(proxy_to_and_forward_response)
        .and_then(log_response);

    // spawn proxy server
    warp::serve(app).run(([0, 0, 0, 0], 3030)).await;
}

Notice that the forwarding of the request is done by the lib, if you actually want examples you can check the source code to investigate how it is done.