Processing HTTP Requests
local graph
Chapter 6 — Processing HTTP Requests
Section titled “Chapter 6 — Processing HTTP Requests”6 Processing HTTP Requests
Section titled “6 Processing HTTP Requests”In the previous chapter, we utilized the Actix web framework to serve basic views. However, this can only get us so far when it comes to extracting data from the request and passing data back to the user. In this chapter, we will build on the code from Chapter 5, to build server views that process to-do items. We will then explore JSON serialization for extracting data and returning it to make our views more user-friendly. We will also extract data from the header with middleware before it hits the view. We will explore the concepts around data serialization and extracting data from requests by building out the create, edit, and delete to-do item endpoints for our to-do application.
In this chapter, we will cover the following topics:
- Passing parameters via the URL
- Passing data via the POST body
- Deleting resources using the DELETE method
- Automating running our server
- Updating resources using the PATCH method
- Extracting data from HTTP request headers
Once you have finished this chapter, you will be able to build a basic Rust server in Actix, Axum, Hyper, or Rocket that can send and receive data in the URL, in the body using JSON, and in the header of the HTTP request. This is essentially a fully functioning API server in Rust without a proper database for data storage, authentication of users, or displaying of content in the browser. However, these concepts are covered in the next three chapters. You are on the home stretch to having a fully working Rust server up and running. Let’s get started!
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files, featuring the implementation of the changes in the core layer from Chapter 5, are included in the downloadable code bundle. You will also be making requests to your server using the cURL command-line tool, which enables you to make network requests. You can download cURL directly through your OS package manager.
Passing parameters via the URL
Section titled “Passing parameters via the URL”Passing parameters via the URL is the easiest way to pass data to the server. We can explore this concept by passing the name of a to-do item and returning that single to-do item to the client.
Before we touch the networking layer, we must build the core function that loads the data and filters for the to-do item by name, which can be done with the following code:
//...
use glue::errors::{ NanoServiceError, NanoServiceErrorStatus};
// ...pub async fn get_by_name(name: &str) -> Result<ToDoItem, NanoServiceError> { Ok(get_all_handle::<ToDoItem>()? .remove(name) .ok_or( NanoServiceError::new( format!("Item with name {} not found", name), NanoServiceErrorStatus::NotFound ) )?}Note that our filter at this stage is essential, as we are loading all the data, extracting the item that we want, and then returning it. We will optimize our filter in Chapter 9 when we move over to a proper database. For now, our filter works for us, so we can continue to develop our features.
We can also see that we use the remove function to extract the item. This means that we do not have to clone the item that we are extracting, reducing the amount of memory required. We do not worry that the item has been removed from the HashMap because we are not going to write that HashMap to the file.
We now need to connect our core get_by_name function to our HTTP server. We will wrap the core get_by_name function in a function that handles the HTTP request, but we first need to expose the core functionality and networking utils by redefining our imports with the following code:
//! File: nanoservices/to_do/networking/actix_server//! src/api/basic_actions/get.rsuse to_do_core::api::basic_actions::get::{get_all as get_all_core, get_by_name as get_by_name_core
};use actix_web::{ HttpResponse, HttpRequest};use glue::errors::{ NanoServiceError, NanoServiceErrorStatus};We can see that we are using the status and the HTTP request. Here, our incoming HTTP request needs to be accepted, and the name parameter must be extracted from the URL.
We then need to handle this extraction. We can do this with the following code:
//! File: nanoservices/to_do/networking/actix_server//! src/api/basic_actions/get.rs
pub async fn get_by_name(req: HttpRequest) -> Result<HttpResponse, NanoServiceError> { let name = match req.match_info().get("name") { Some(name) => name, None => { return Err( NanoServiceError::new( "Name not provided".to_string(), NanoServiceErrorStatus::BadRequest ) ) } }; Ok(HttpResponse::Ok().json(get_by_name_core(name).await?))}Here, we can see that if the name parameter is not found in the URL, we return a bad request. We then just return the data from the core get_by_name function, exploiting the ? operator at the bottom of the function, as a not found HTTP response will be automatically returned to the client if the item is not found. We have nearly finished our get API endpoint. All we must do now is connect our API endpoint to our factory. We can do this by adding the following line:
//! File: nanoservices/to_do/networking/actix_server//! src/api/basic_actions/mod.rs....route("get/{name}", get().to(get::get_by_name))...We need to have that to-do item in our tasks.json JSON file in the root of our system. If we do not have the JSON file in the root, the server will look for the JSON file to access the state of to-do items and not find the file, returning an error. With the JSON file, we can run our server with the following command:
cargo run -p to-do-actix-serverWhile our server is running, we can visit our individual get URL in the browser. We will get a response like the following:
Figure 6.1 – Our response from our individual GET endpoint
If we pass a to-do item name that we know is not in the JSON file, we will get a not found response, as seen in Figure 6.2.
Figure 6.2 – Our not found response from our individual GET endpoint
And here we have it, our get individual to-do item is now fully working.
[figure outside: Figure 6.1] [figure outside: Figure 6.2]
Remember the flexibility we have with our network layer!
It is reasonable to wonder why we have two different layers to just get the simple filter that returns one item. Remember, our core functionality is separated from the networking layer; therefore, we can swap out the web framework easily if we need to. Also, more importantly, we can compile this nanoservice into another program or server by just targeting the core workspace. It is important to keep this flexibility in mind to justify the effort of maintaining these layers.
You can inspect the code on GitHub to see how the other frameworks extract the name from the URL:
-
Rocket: The
is nested in the route macro above the function that serves the API endpoint. -
Axum: The Path struct is wrapped around the name variable and placed as a parameter in the function that serves the endpoint. This Path struct acts as an extractor that implements a trait that extracts data from the request. We will learn how to implement these traits for Actix. The approach of implementing extractor traits is pretty much the same for Rocket and Axum.
-
Hyper: Here, the URI is split into a vector and matched. The function that is called with the request depends on the match arm from the URI.
Even though we can get our to-do items, we cannot yet do much with them. We must start altering the state of our to-do items. Our next step is refactoring our create to-do item via POST and JSON data.
Passing data via POST body
Section titled “Passing data via POST body”While passing parameters via the URL is simple, there are a few problems with the URL approach. URLs can be cached by the browser, and the user might end up selecting an autocompleted URL with data in the URL. This is good if we are using the URL to pass parameters to get data, such as visiting your profile on a social media application; however, we do not want to accidentally select a cached URL that alters data in the application. In this section, we are going to explore POST requests by creating a new to-do item and returning all the to-do items.
Passing data in the URL is also limited to simple data types. For instance, if we wanted to pass a list of HashMaps to the server, it would be hard to pass such a data struct through the URL without doing some other form of serialization. This is where POST requests and JSON bodies come in. We can pass JSON data via the HTTP request body.
Defining the core create function
Section titled “Defining the core create function”We have already built our create function, but we need to refactor it so that we can integrate the create function into our web server. Our create function refactor results in the following code:
use crate::structs::ToDoItem;#[cfg(feature = "json-file-storage")]use to_do_dal::json_file::save_one;use glue::errors::NanoServiceError;
pub async fn create(item: ToDoItem) -> Result<ToDoItem, NanoServiceError> { let _ = save_one(&item.title.to_string(), &item)?; Ok(item)}Remember that our ToDoItem struct has already implemented the serializing structs to be read and written to the JSON file. Here, we have turned our create function into an async function. Right now, we are not using any async functionality, but in the future, we will be using async to connect to databases and make HTTP requests inside our API endpoints. Considering this, it makes sense just to make API functions in the core module async. If you kept the main.rs file in the core workspace, you now must delete it, or convert the main function in the main.rs file into async and pass a constructed ToDoItem into the create function.
We can now wrap the core create function in our server.
Wrapping our core in the networking layer
Section titled “Wrapping our core in the networking layer”First, we need to use the following:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/create.rsuse to_do_core::api::basic_actions::{ create::create as create_core, get::get_all as get_all_core};use to_do_core::structs::ToDoItem;use glue::errors::NanoServiceError;use actix_web::{ HttpResponse, web::Json};With these structs and traits, we can define our create API web endpoint with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/create.rs
pub async fn create(body: Json<ToDoItem>) -> Result<HttpResponse, NanoServiceError> { let _ = create_core(body.into_inner()).await?;Ok(HttpResponse::Ok().json(get_all_core().await?))}Wow, that is compact! But there is a lot going on here. The Json struct implements traits that extract data from the body of the HTTP request before the create function is called. If the HTTP request body can be serialized into a ToDoItem struct, then this is done, and we have a ToDoItem struct passed into the create function from the HTTP request body. If a ToDoItem struct cannot be constructed from the JSON body of the HTTP request, then a bad request response is returned to the client with the serialization error message.
The Json
Finally, we get all the data from the JSON file with the get_all_core function and return the items in a JSON body. Again, this is not optimal as our JSON file is not a replacement for a proper database, but it will work for now for creating a new to-do item and returning all the to-do items.
At this stage, we can take a step back and appreciate the consistency that the three major alternative web frameworks have achieved. While we have not coded them directly in this book, they are available in the GitHub repo. For our Axum networking layer, our create API endpoint takes the following form:
//! File: nanoservices/to_do/networking/axum_server//! /src/api/basic_actions/create.rs...pub async fn create(Json(body): Json<ToDoItem>) -> Result<impl IntoResponse, NanoServiceError> { let _ = create_core(body).await?; let all_items = get_all_core().await?; Ok((StatusCode::OK, Json(all_items)))}To avoid bloating the chapter, the imports and routing are defined in the GitHub repository. Here, we can see that we are using Axum’s JSON extractor. Because our functions, errors, and structs implement the serde Serialize and Deserialize traits, and our errors convert to HTTP responses, our integration for other frameworks is still minimal.
For our Rocket implementation, we have the following function:
//! File: nanoservices/to_do/networking/rocket_server//! /src/api/basic_actions/create.rs...#[post("/create", data = "<body>")]pub async fn create(body: Json<ToDoItem>) -> Result<Json<AllToDoItems>, NanoServiceError> { let _ = create_core(body.into_inner()).await?; Ok(Json(get_all_core().await?)) }Again, we just use the JSON extractor that Rocket has provided. Finally, our Hyper server is a little more involved; we do not have the from request extractors, so we must build our own body extractor with the following code:
//! File: nanoservices/to_do/networking/hyper_server//! /src/utils.rs…
pub async fn extract_body<X: DeserializeOwned> (req: Request<Incoming>) -> Result<X, NanoServiceError> { let whole_body = safe_eject!( req.collect().await, NanoServiceErrorStatus::BadRequest )?.aggregate(); let body: X = safe_eject!( serde_json::from_reader(whole_body.reader()), NanoServiceErrorStatus::BadRequest, "Failed to parse JSON body" )?; Ok(body) }We then use this body extraction function for our create API endpoint with the following code:
//! File: nanoservices/to_do/networking/hyper_server//! /src/api/basic_actions/create.rs…
pub async fn create(req: Request<Incoming>) -> Result<Response<Full<Bytes>>, NanoServiceError> { let todo_item = extract_body::<ToDoItem>(req).await?; create_core(todo_item).await?; let json_body = safe_eject!( serde_json::to_string(&get_all_core().await?), NanoServiceErrorStatus::Unknown )?; safe_eject!(Response::builder() .header(header::CONTENT_TYPE, "application/json") .body(Full::new(Bytes::from(json_body))), NanoServiceErrorStatus::Unknown )}This is because we manually match the URI and pass the entire HTTP request into the function. Therefore, we must do the conversions ourselves. However, our safe_eject! macro really helps consistent with minimal code.
Can we pass a JSON body in a GET instead of a POST request?
Yes, we can. Personally, I find these method definitions trivial, and I like to put all the data that I am passing to the server in a JSON body because it is easier to handle as the requirements and app evolve. I also find it easier to handle the serialization into a struct. However, this is just my opinion, and while most HTTP clients will allow you to put JSON bodies in a GET request, at the time of writing this book, Axios, a JavaScript HTTP client, will not allow JSON bodies in GET requests. There is also the added risk of intermediaries such as proxies and load balancers that might not expect a JSON body in a GET request and reject it. Depending on the configuration of the server, GET requests with JSON bodies could be classified as “request smuggling,” where an attacker tries to attach data to a request that is not supposed to be there.
I’ve worked on projects where I have put everything through POST methods, and while this means that the requests are not cached, for the initial phase, it has worked out fine. This means I can keep altering the bodies until I am happy with the structure. These requests can be refined later. You can read about the semantics of HTTP requests via the following link: https://www.rfc-editor.org/rfc/rfc9110.
After adding a couple of create files, it is worth running a cargo build command in the root of your system to make sure that your build is working before progressing.
We now need to plug our create API function into our web server.
Configuring our create network route
Section titled “Configuring our create network route”We start by importing the post function with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs...use actix_web::web::{ServiceConfig, get, scope, post};...158Processing HTTP Requests
We then define our view in our factory with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs....route("create", post().to(create::create))...We can now run our server with our new create endpoint.
Testing our endpoint with cURL
Section titled “Testing our endpoint with cURL”While our server is running, we can test our create endpoint with the following cURL command in our terminal:
curl -X POST http://127.0.0.1:8080/api/v1/create \-H "Content-Type: application/json" \-d '{"title": "writing", "status": "PENDING"}'If you are using Windows 11, you might have some problems with cURL leveraging PowerShell under the hood, meaning that Windows 11 is not directly using cURL. This “fake cURL” might not work. You can get around this by using HTTP files, which is explained at the following link: https://learn.microsoft.com/en-us/aspnet/core/test/http-files?view=aspnetcore-8.0.
For our cURL command, we can see that we include an -H flag. This is a header, telling the server that our request contains JSON. This can help the server with processing the request to decide if the server can process the request body as JSON. As mentioned before, some servers and load balancers can reject the request if the header does not match the contents under the suspicion of request smuggling.
After the cURL command has been run, we then get the following response:
{ "pending": [ {"title":"writing","status":"PENDING"}, {"title":"washing","status":"PENDING"} ], "done": [ {"title":"coding","status":"DONE"} ]}If we inspect our JSON file that we are using for storage, we should have the following contents:
{ "coding": {"title": "coding","status": "DONE"},"writing": {"title": "writing","status": "PENDING"},"washing": {"title": "washing","status": "PENDING"}}We can also test our serialization of the JSON body with the following command, to check that our API endpoint will not accept any status. If we were to accept any status, we would not be able to sort the to-do items into pending or done:
curl -X POST http://127.0.0.1:8080/api/v1/create \-H "Content-Type: application/json" \-d '{"title": "writing", "status": "test"}'The preceding command has a status that should not be accepted. When we run this command, we should get the following response:
Json deserialize error: unknown variant `test`, expected `DONE`or `PENDING` at line 1 column 37With this response, we can see that we are not going to be passing data that is going to corrupt the data store, and we get a helpful response on why we are rejecting the incorrect data.
This guard will also work for Axum, Rocket, and Hyper because we have defined the serialization rules in our core module for the ToDoItem struct, meaning that we will only accept pending and done status tasks.
And there we have it. We can see that our POST create HTTP endpoint is now working. So, we can now get our items and add new ones. However, what if we create an item by accident and need to delete it? This is where DELETE methods come in.
Deleting resources using the DELETE method
Section titled “Deleting resources using the DELETE method”DELETE methods are like GET methods. We could technically pass data in the JSON body of the HTTP request, but it is not standard practice like the GET method. For our DELETE post, there should be enough data in the URL that we can perform a delete. In our case, the title of the item is enough to delete the item from storage, for the sake of simplicity.
Defining our delete JSON file method
Section titled “Defining our delete JSON file method”Before we define the core and server functions, we must ensure that our data access layer function returns the right message if we do not find the right item when deleting from our store. Some slight refactoring is needed where we return the right error if there is no item found in the store, using the following code:
pub fn delete_one<T>(id: &str) -> Result<T, NanoServiceError>where T: Serialize + DeserializeOwned + Clone + std::fmt::Debug,{ let mut tasks = get_all::<T>().unwrap_or(HashMap::new()); match tasks.remove(id) { Some(deleted_item) => { save_all(&tasks)?; Ok(deleted_item) }, None => Err( NanoServiceError::new( format!("Task with title {} not found", id), NanoServiceErrorStatus::NotFound ) ) }}We can now define our core delete function with the following code:
use to_do_dal::json_file::delete_one;use crate::structs::ToDoItem;use glue::errors::NanoServiceError;
pub async fn delete(id: &str) -> Result<ToDoItem, NanoServiceError> { delete_one::<ToDoItem>(id)}We can then wrap the core delete function into our networking layer. The approach should run along the same lines as the get individual item API endpoint, as we are extracting the name parameter out of the URL. Now would be a good time to try and build the delete endpoint function for the server yourself.
Adding delete to our networking layer
Section titled “Adding delete to our networking layer”If you attempted to build the delete endpoint function yourself, hopefully you will have used the following structs and traits:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/delete.rsuse to_do_core::api::basic_actions::{ delete::delete as delete_core, get::get_all as get_all_core};use actix_web::{ HttpResponse, HttpRequest};use glue::errors::{ NanoServiceError, NanoServiceErrorStatus};We then define the delete endpoint with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/delete.rs
pub async fn delete_by_name(req: HttpRequest) -> Result<HttpResponse, NanoServiceError> { match req.match_info().get("name") { Some(name) => { delete_core(name).await?; }, None => { return Err( NanoServiceError::new( "Name not provided".to_string(), NanoServiceErrorStatus::BadRequest ) ) } }; Ok(HttpResponse::Ok().json(get_all_core().await?))}162
Processing HTTP Requests
We return a 200 OK status code. However, technically, our semantics are not correct. The body should be a status of what is deleted. This is why the core delete function returned the item that was deleted. However, here we return all the to-do items instead. This is to simplify our frontend when we start coding it as we will not have to make another HTTP request once we have performed an action on our to-do items.
Defining the delete route
Section titled “Defining the delete route”We now need to plug our delete_by_name API function into our web server. To do this, firstly we need to import the delete function with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs...use actix_web::web::{ServiceConfig, get, scope, post, delete};...We then define our view in our factory with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs....route("delete/{name}", delete().to(delete::delete_by_name))If we then run our server, we can make a delete request with the following command:
curl -X DELETE http://127.0.0.1:8080/api/v1/delete/washingHowever, we get the following error when making the request:
“Error parsing JSON file: trailing characters at line 10 column 4”
Thanks to all the effort that we put into our error handling, we know that there is something wrong with the parsing of the JSON file. Our safe_eject! macro has a string that has the context added to the error. So, if we go to our nanoservices/to_do/dal/src/json_file.rs file and search for “Error parsing JSON file”, we will see that the error is occurring when we try and serialize the data loaded from the JSON file.
Refactoring our JSON file code
Section titled “Refactoring our JSON file code”If we inspect our JSON file, we should have something like the following:
{"coding": {"title": "coding","status": "DONE"},"washing": {"title": "washing","status": "PENDING"}"washing": {"title": "washing","status": "PENDING"}In the JSON file contents, we can see that there is some malformed JSON, implying that the file is not being cleared or truncated before writing the JSON data to the file. To fix this, we need to revert the JSON file to the previous state. We then must create a writer handle that truncates the file, ensuring that the file is empty before we write to the file with the following code:
fn get_write_handle(path: Option<&str>) -> Result<File, NanoServiceError> { let path = match path { Some(p) => p, None => { &env::var("JSON_STORE_PATH").unwrap_or( "./tasks.json".to_string() ) } }; let file = safe_eject!(OpenOptions::new() .write(true) .create(true) .truncate(true) // ensures file is empty .open(&path), NanoServiceErrorStatus::Unknown, "Error reading JSON file (write handle)" )?; Ok(file)}Because the handle ensures that the file is empty, we will not get any parsing errors when writing our updated state to our JSON file. We can then swap our file handle in the save_all function with the following code:
pub fn save_all<T: Serialize>(tasks: &HashMap<String, T>)-> Result<(), NanoServiceError> { let mut file = get_write_handle(None)?; ... Ok(())}Now that the data access layer has been refactored, we must recompile our code. We then rerun our delete cURL command, and we should get the following printout in the terminal:
{ "pending":[],
"done":[ {"title":"coding","status":"DONE"} ]}This shows that we have successfully deleted our to-do item!
For the other web frameworks, we are using methods that we have seen before, so the examples in the GitHub repo should make sense.
In this section, we got to see how useful the context of the error was as our error bubbles up to the HTTP response, so our system is not panicking. However, we also do not get a stack trace because the server has not crashed.
We are now at the stage where there are a few moving pieces and different endpoints. At this stage, it is good to start automating some of these steps so we can quickly check that our system is working as it should. Later, I dedicate two entire chapters to testing, as testing is a fundamental skill for keeping up the momentum of software development. However, to prevent frontloading too many concepts at once, we can build a basic Bash script that populates the JSON file with a state that we want and then performs some HTTP requests so we can inspect the output.
Automating running our server
Section titled “Automating running our server”To create the automated Bash script that orchestrates an end-to-end test, we must create a scripts directory and create a Bash file called basic_test.sh within it. We then create some boilerplate code that navigates to the root of our system, as follows:
#!/usr/bin/env bash
File: scripts/basic_test.sh
Section titled “File: scripts/basic_test.sh”navigate to directory
Section titled “navigate to directory”SCRIPTPATH=“(dirname “SCRIPTPATH cd ..
The first line of the preceding code is called a shebang line, which tells the computer that we are to execute the script using our shell. We then navigate to the directory where this script is and then move out one directory to be in the root. This is done because Bash scripts run in whatever working directory calls them. Because we are looking for specific files and we want to run our server, we want to ensure that our testing script runs in the root of the system every time we run the testing script, no matter where we call it from.
If you downloaded the GitHub repository, the functionality of our server will also work with Hyper, Axum, and Rocket. Therefore, we want the option to build and run any of these servers with the following code:
File: scripts/basic_test.sh
Section titled “File: scripts/basic_test.sh”framework=framework in actix) echo “Building and running Actix server…” cargo build -p to-do-actix-server cargo run -p to-do-actix-server & PID=$!
;;axum) echo “Building and running Axum server…” cargo build -p to-do-axum-server cargo run -p to-do-axum-server & PID=$!
;;hyper) echo “Building and running Hyper server…” cargo build -p to-do-hyper-server cargo run -p to-do-hyper-server & PID=$!
;;rocket) echo “Building and running Rocket server…” cargo build -p to-do-rocket-server cargo run -p to-do-rocket-server & PID=$!
;;*) echo “Unknown framework: $framework”
echo "Usage: $0 [actix|axum|hyper|rocket]"exit 1;;esacsleep 1If we do not pass in any arguments to the Bash script, our default server that will run is Actix. With the & character, we are running the server in the background. We build the server before we run it, because we do not want to be compiling our server in the background while we are making HTTP requests to it. We then keep track of the process ID by assigning it to the variable PID, and we sleep for one second to ensure that the server is ready for HTTP requests. We will use the PID to kill the server after our HTTP requests have been carried out because the tests have finished, and we do not want a server running indefinitely, binding a port after the tests. We then remove our tasks.json file and create a new one with the state that we want, with the following code:
File: scripts/basic_test.sh
Section titled “File: scripts/basic_test.sh”rm tasks.json
rm output.txt
cat <
We are keeping the state empty, but we could put any JSON state we wanted in the curly brackets. This ensures that the state is consistent every time we run the test, so we can see whether a change in our code later changes the behavior of our server.
Now that our state is defined, and our server is running in the background, we can test our API endpoints with the following code:
File: scripts/basic_test.sh
Section titled “File: scripts/basic_test.sh”curl -X POST http://127.0.0.1:8080/api/v1/create
-H “Content-Type: application/json”
-d ’{“title”: “writing”, “status”: “PENDING”}’ >> output.txt
echo "" >> output.txt
curl -X POST http://127.0.0.1:8080/api/v1/create \ -H "Content-Type: application/json" \ -d '{"title": "coding", "status": "PENDING"}' >> output.txt
echo "" >> output.txt
curl -X DELETE http://127.0.0.1:8080/api/v1/delete/coding >> output.txtkill $PIDHere, create a couple of pending items, and then delete one of the items. We also append the state of the items to the output.txt file after every request so we can see how the state progresses after each HTTP request.
We now run our Bash script with the following command:
sh scripts/basic_test.shWe should get the following contents in our output.txt file:
{“pending”:[{“title”:“writing”,“status”:“PENDING”}],“done”:[]}
{ "pending":[{"title":"coding","status":"PENDING"}, {"title":"writing","status":"PENDING"}],"done":[]}}{“pending”:[{“title”:“writing”,“status”:“PENDING”}],“done”:[]}
Here, we can see that our delete and create API endpoints affect the state as expected. And there we have it; we can run this script again and again with consistent outcomes. We will keep adding to this script, and over time, you will get a feel for how much time building a testing harness saves you.
Deleting the to-do item titled writing is all well and good, but we also need to be able to edit the status of the to-do item. In our next section, we will edit our to-do items with PATCH methods.
Updating resources using a PATCH method
Section titled “Updating resources using a PATCH method”PATCH methods are essentially the same as a POST method. We want to put the data in the JSON body. However, the PATCH method is typically used for updating parts of a resource that have already been created. If we were to update the entire resource, then we would use the PUT method.
This is the last endpoint that we create in this chapter. Here, we want to accept a to-do item in the JSON body, get the item, and update it. This is a good point to try and build the API endpoint yourself. As a hint, it is advisable to start with the core, calling the data access layer. Here, you can load the items, check that the item is there, and update the item, inserting the updated item back into the state and writing the state. Once this is done, you then move on to the networking layer, which calls the core update function.
To build our API endpoint, we begin by importing the following:
use to_do_dal::json_file::{ get_all as get_all_handle, save_all};use crate::structs::ToDoItem;use glue::errors::{ NanoServiceError, NanoServiceErrorStatus};With these imports, we define the update function with the following code:
pub async fn update(item: ToDoItem) -> Result<(), NanoServiceError> { let mut all_items = get_all_handle::<ToDoItem>()?; if !all_items.contains_key(&item.title) { return Err(NanoServiceError::new( format!("Item with name {} not found", item.title), NanoServiceErrorStatus::NotFound )); } all_items.insert(item.title.clone(), item); save_all(&all_items)?; Ok(())}Here, we can see that we get all the items, and check to see whether the item we are trying to update is in the state of our to-do items. If it’s not, we return an error.
Note that if we were using a PUT method, it is customary to allow the creation of the resource if the resource is not there. However, for us, we are only doing a partial update, which is the status. In our frontend, our update will only happen if the user clicks on a button associated with the to-do item. The item must be there before we can update it. If it is, we then update the item with the new status and save it.
Everything is ready here to move on to defining the API function for the server, which takes the following form:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/update.rsuse to_do_core::api::basic_actions::{ update::update as update_core, get::get_all as get_all_core};use to_do_core::structs::ToDoItem;use glue::errors::NanoServiceError;use actix_web::{ HttpResponse, web::Json};
pub async fn update(body: Json<ToDoItem>) -> Result<HttpResponse, NanoServiceError> {let _ = update_core(body.into_inner()).await?;Ok(HttpResponse::Ok().json(get_all_core().await?))}The preceding code should not be a surprise at this point. We are merely extracting the correct data from the HTTP request, calling a core function, and returning an HTTP response.
Finally, we import the PUT method with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs...use actix_web::web::{ServiceConfig, get, scope, post, delete, patch};...We also define the API endpoint view in the API factory with the following code:
//! File: nanoservices/to_do/networking/actix_server//! /src/api/basic_actions/mod.rs....route("update", patch().to(update::update))...We can now update our testing Bash script with the update API call using the following code:
File: scripts/basic_test.sh
Section titled “File: scripts/basic_test.sh”… echo "" >> output.txt
curl -X PATCH http://127.0.0.1:8080/api/v1/update \ -H "Content-Type: application/json" \ -d '{"title": "writing", "status": "DONE"}' \ >> output.txtkill $PIDWith this addition, running the test Bash script gives us the following content in the output.txt file:
{“pending”:[{“title”:“writing”,“status”:“PENDING”}],“done”:[]}
{ "pending":[{"title":"coding","status":"PENDING"}, {"title":"writing","status":"PENDING"}],"done":[]}{“pending”:[{“title”:“writing”,“status”:“PENDING”}],“done”:[]} {“pending”:[],“done”:[{“title”:“writing”,“status”:“DONE”}]} The content in the output.txt file shows that our update API endpoint works. And this is it, we have all our endpoints to handle to-do items. But what about extracting data from headers? While we do not need to extract anything from HTTP request headers to handle our to-do items, we will need to extract data from headers for things such as authentication. Extracting data from headers comes under the concept of processing HTTP requests.
Extracting data from HTTP request headers
Section titled “Extracting data from HTTP request headers”In this section, we will not implement full authentication, as this will be addressed in Chapter 10. Here, we are just going to extract a string from the header.
Before we write any more code, we must add the following dependency to our glue module as we will be using futures in our implementation of the extractor traits:
...[dependencies]...futures = "0.3.30"When it comes to headers, we can store credentials or metadata around the HTTP request. Before we get into inspecting the headers of our HTTP requests, we must define our token in our glue workspace because we are going to use the token for authentication in the future. Every service should have the right to enforce authentication without having to rewrite the token implementation.
Defining our header token modules
Section titled “Defining our header token modules”We want our glue module to support header extraction for all our different web frameworks. Therefore, our token.rs file has the following imports and structure:
pub struct HeaderToken { pub message: String,}#[cfg(feature = "actix")]mod actix_impl { use super::HeaderToken; pub use actix_web::{ dev::Payload, FromRequest as ActixFromRequest, HttpRequest, }; use futures::future::{Ready, ok, err}; use crate::errors::{NanoServiceError, NanoServiceErrorStatus}; ...}#[cfg(feature = "rocket")]mod rocket_impl { ...}#[cfg(feature = "axum")]mod axum_impl { ...}#[cfg(feature = "actix")]pub use actix_impl::ActixFromRequest;Here, we can see that we wrap the implementation of the FromRequest trait inside its own module to avoid clashes. We are not going to cover the implementations of the other frameworks; however, Rocket and Axum are pretty much the same as Actix. The working code is in the GitHub repository for reference.
Because we are handling the API view functions directly with Hyper, the extract body and token from header functions have been moved to a hyper_utils directory in the glue module. Finally, we can see in the preceding code that we export our ActixFromRequest trait at the bottom of the file if we need to reference it outside of the file. (In the GitHub code repository, we also export the other web frameworks, but if you are not implementing the other frameworks, then it is best to just export the web frameworks that you are implementing.)
As we can also see, the HeaderToken struct houses a string, which is going to be the token extracted from the header.
Implementing an Actix header extraction trait
Section titled “Implementing an Actix header extraction trait”Now we move on to building the middleware that extracts the token inside our Actix module, using the following code:
impl ActixFromRequest for HeaderToken { type Error = NanoServiceError; type Future = Ready<Result<HeaderToken, NanoServiceError>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ... }}Here, we return a result that can be either our nanoservice error or a header token. The Ready struct wraps this result and implements the Future trait, where the poll function instantly returns a Ready state with the result. We can see this code in the futures package:
//! package: futures::futureimpl<T> Future for Ready<T> { type Output = T; #[inline] fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<T> { Poll::Ready(self.0.take().expect( "Ready polled after completion") ) }}What this means is that our from_request function returns a future that is going to be processed by our tokio runtime. However, that future is going to instantly be resolved after one poll, which is why there is no waker in the poll function of the Ready struct.
Now that we understand what our from_request function does, let’s focus on the code inside the from_request function. Initially, we must extract the token from the header and return an unauthorized error if there is no token, using the following code:
let raw_data = match req.headers().get("token") { Some(data) => data, None => { return err(NanoServiceError { status: NanoServiceErrorStatus::Unauthorized, message: "token not in header under key 'token'" .to_string() }) }};Note that we return an error wrapped in err. Lowercase err and lowercase ok just wrap the error or result in a Ready struct.
Now that we have extracted the data from the header, we can then convert the data to a string and return it with the code:
let message = match raw_data.to_str() {Ok(token) => token.to_string(),Err(_) => { return err(NanoServiceError { status: NanoServiceErrorStatus::Unauthorized, message: "token not a valid string".to_string() })}};return ok(HeaderToken{message})Our token is now ready to extract data from the header in the middleware.
Extracting headers from requests in the Actix networking layer
Section titled “Extracting headers from requests in the Actix networking layer”Finally, to make the token code accessible to users of our token module, we can declare the token module in our glue crate with the following code:
pub mod errors;pub mod token;We can now update our update API endpoint with the following code:
//! File: nanoservices/to_do/networking/actix_server///! src/api/basic_actions/update.rs...use glue::{ errors::NanoServiceError, token::HeaderToken};...pub async fn update(token: HeaderToken, body: Json<ToDoItem>) -> Result<HttpResponse, NanoServiceError> { println!("Token: {}", token.message); let _ = create_core(body.into_inner()).await?; Ok(HttpResponse::Ok().json(get_all_core().await?))}Here, we can see that putting the HeaderToken as a parameter in the create function will execute the FromRequest trait and pass the result into the function if the FromRequest trait passes. This is the same as our Json
Right now, for our token extraction implementations, we can only extract a string; however, in Chapter 10, we will upgrade our token to hold the user ID and encrypt the data.
If we now run our basic test Bash script, we get the following contents:
## File: outcome.txt{"pending":[{"title":"writing","status":"PENDING"}],"done":[]}{"pending":[ {"title":"coding","status":"PENDING"}, {"title":"writing","status":"PENDING"}],"done":[]}{"pending":[{"title":"writing","status":"PENDING"}],"done":[]}"token not found in request header"Here, we can see that our create and delete HTTP calls are working. However, our update did not work, as we did not have a token in the header. This is what we want because we now require our update API endpoint to have a token in the header.
We can add a token to our header with the following code:
...curl -X PATCH http://127.0.0.1:8080/api/v1/update \ -H "Content-Type: application/json" \ -H "token: some token" \ -d '{"title": "writing", "status": "DONE"}' >> output.txtkill $PIDNow that we have added a token, if we run our script again, we will see that our update works and that our state is back to normal. We can now slot in requirements for tokens in the header for any of our API endpoints.
Summary
Section titled “Summary”In this chapter, we have put all of what we learned in the previous chapters to good use. We fused the logic from the core, which loads and saves to-do items from a JSON file, and looked at the to-do item process logic by using the basic views from Actix-web. With this, we have seen how the isolated modules click together. We will keep reaping the benefits of this approach in the next few chapters as we rip out the JSON file and replace it with a database.
We also managed to utilize the serde crate to serialize complex data structures. This allows our users to get the full state update returned to them when they make an edit. We can see that the power of Rust enables us to do some highly customizable things to our server, without us having to dig deep into the framework.
Rust has a strong future in web development. With a few lines of code, we can build our own middleware. Our JSON serialization structs were made possible with just one line of code, and the traits provided by Actix enabled us to define the parameter in the view function, thus enabling the view to automatically extract the data from the body and serialize it into the struct. This scalable, powerful, and standardized way of passing data is more concise than many high-level languages. We can now fully interact with and inspect every part of the HTTP request. What’s more, the consistency of extracting JSON from bodies and tokens from headers is consistent across Rocket, Axum, and Actix. This is a testament to the trait-based approach for Rust in general.
Now that we are processing and returning well-structured data to the user, we can start displaying it in an interactive way for our user to point and click when editing, creating, and deleting to-do items.
In the next chapter, we will be serving HTML, CSS, and JavaScript from the Actix-web server. This will enable us to see and interact with to-do items via a graphical user interface, with the JavaScript making API calls to the endpoints we defined in this chapter.
You may feel the urge to keep up the momentum of building a better API by adding a database now. However, with the frontend, there are a fair number of moving parts, and it is easier to establish the frontend and run/handle Docker at the same time, as we will be using Docker to run isolated databases.
Questions
Section titled “Questions”-
What is the difference between a GET and a POST request?
-
Why would we have middleware when we check credentials?
-
How do you enable a custom struct to be directly returned in a view?
-
How do you enact middleware for the server?
-
How do you enable a custom struct to serialize data into the view?
Answers
Section titled “Answers”-
A GET request can be cached, and there are limits to the types and amount of data that can be sent. A POST request has a body, which enables more data to be transferred. Also, it cannot be cached.
-
We use middleware to open the header and check the credentials before sending the request to the desired view. This gives us the opportunity to prevent the body from being loaded by returning an auth error before loading the view, preventing the potentially malicious body.
-
For the struct to be directly returned, we will have to implement the Responder trait. During this implementation, we will have to define the responded_to function that accepts the HTTP request struct. The responded_to function will be fired when the struct is returned. Processing HTTP Requests
-
To enact middleware, we can implement the FromRequest trait for a struct, and then pass that struct as a parameter in the function of the API endpoint.
-
We decorate the struct with the #[derive(Deserialize)] macro. Once we have done this, we define the parameter type to be wrapped in a JSON struct: parameter: web::Json
.
Learn more on Discord
Section titled “Learn more on Discord”To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow this QR code: https://packt.link/EaKXL