How to send a PNG of a QR-code in a HTTP response body

I have a api route in

rust axum which get's an item data from the database and generate a qrcode from the item data. How do i send the generated qr code in the response? Here is my code:

pub async fn get_qr_code(
    Path(item_id): Path<i32>,
    pool: Arc<PgPool>,
) -> impl IntoResponse {
    // Get the product details from the database
    let result:Vec<Product>= query_as!(
        Product,
        "SELECT *
         FROM items i
         WHERE i.id = $1",
         item_id
    )
    .fetch_all(&*pool)
    .await
    .expect("Failed to fetch product id");

    if let Some(first_item) = result.get(0) {

        let qr_code_data = format!(
            "id={}&name={}&title={}",
            first_item.id,
            first_item.name,
            first_item.title
        );
    
        // Create the QR code
        let qr_code = QrCode::new(qr_code_data.as_bytes()).unwrap();
        let qr_image = qr_code.render::<Luma<u8>>().build();

        // return the QR code  image as a response

        // Return the JSON response with the QR code image
        // Ok(IntoResponse::Ok().json(response_json))

      

    

    }

    Json(json!([]))

   
}

Thank you in advance.

What would be an example of JSON response with the QR code image? JSON is a text protocol. There's no obvious way to embed any image within JSON, especially as a visible image.

I don't really need the JSON response, all I want is to return the QR code image as response after generating it

Thanks.

Then I'd encode it as webp and return it:

let mut qr_image = Vec::new();
qr_code.render::<Luma<u8>>()
    .build()
    .write_to(&mut qr_image, image::ImageFormat::WebP)
    .unwrap();

axum::response::Response::builder().header("content-type", "image/webp").body(qr_image)
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.