1

Have spent some time learning Rust and have now moved to looking at web based applications. Using the Rocket crate in rust I have explored the GET request method and understood this well. Now have a POST request in my code and it runs, but I am unsure how to actually POST a new book into my dummy database? How can I test the code to check that a received REQUEST is adding a new book?

I am working on MacOS.

Sorry am very new to this - so grateful for any help!

#![feature(decl_macro)]
#[macro_use] extern crate rocket;

use rocket::response::content::Json;
use rocket::request::Form;

#[get("/hello")]
fn hello() -> Json<&'static str> {
   Json("{
     'status': 'success',
     'message': 'Hello API!'
     'server': 'live'
   }")
    }

#[derive(FromForm, Debug)]
struct Book {
    title: String,
    author: String,
    isbn: String
  }

  #[post("/book", data = "<book_form>")]
  fn new_book(book_form: Form<Book>) -> String {
    let book: Book = book_form.into_inner();
    let mut dummy_db: Vec<Book> = Vec::new();
    dummy_db.push(book);
    format!("Book added successfully: {:?}", dummy_db)
  }

fn main() {
    rocket::ignite()
        .mount("/api", routes![hello])
        .mount("/book", routes![new_book])
        .launch();
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41
Kapi
  • 49
  • 5
  • I'm not sure what you mean by "test". Do you just want to try it out a few times? If so, [curl can do POST](https://stackoverflow.com/a/12667839/401059), but [HTTPie](https://stackoverflow.com/a/58977608/401059) is nicer, imho. – Caesar Feb 05 '22 at 14:23
  • 2
    Tools like postman will let you manually send a POST request. However, Rocket has its own built-in testing framework, that avoids doing real networking. Have a look at their docs: https://rocket.rs/v0.4/guide/testing/ . This lets you build a test request in Rust code, check its response in Rust code, and run it using `cargo test` and `#[test]` just like any other Rust test – cameron1024 Feb 05 '22 at 14:56
  • Thanks - looks like curl gives me away of posting. Will also checkout the testing guide as well. – Kapi Feb 05 '22 at 16:46

0 Answers0