1 year ago

#141026

test-img

Kapi

How do I test a POST request?

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();
}

rust

rocket

0 Answers

Your Answer

Accepted video resources