This chapter expands the Q&A service from a single read-only endpoint into a more complete REST-style API. It introduces in-memory storage as a temporary stand-in for a future database, then shows how to share that state safely across Warp route handlers and asynchronous threads. Along the way, the codebase is reshaped to make requests and responses more realistic, while still keeping the implementation focused on Rust fundamentals rather than framework-specific tricks.
The chapter first builds a local store for questions using a hash map, then loads initial data from a JSON file with Serde so the application can start with example content instead of hardcoded values. It explains why custom key types must derive comparison and hashing traits, how to pass shared state into handlers through Warp filters, and how to read from the store when serving GET requests. It also introduces query parameters for pagination, demonstrates how to parse and validate them, and adds custom error types so malformed requests can be handled cleanly instead of crashing the server.
After the read path is in place, the chapter adds the rest of the CRUD workflow: creating questions with POST, updating them with PUT, deleting them with DELETE, and handling malformed JSON bodies. It then extends the service to accept answers sent as form-encoded data, showing how Warp can parse different body formats into Rust types. The final result is a more capable API that supports shared mutable state, better error reporting, and multiple request styles, while leaving room for further improvements such as stronger validation, cleaner IDs, and more complete edge-case handling.
We implemented the GET route for questions in chapter 3; this chapter covers POST, PUT, and DELETE, as well as adding comments via POST.
Reassigning a complex data type like String to another variable requires internally moving ownership over to the new variable and dropping the old one.
Instead of dropping the value x, Rust increments the Arc count. Whenever x or y are going out of scope, Rust decreases the count until it is at 0, and then calls .drop to remove the value from the heap.
We expect new questions in the body of the HTTP POST request on the /questions path.
The PUT method adds a URL parameter that we need to parse via Warp and add to our route handler.
The last method to fully implement the questions resource is HTTP DELETE.
The last route we are implementing: adding answers via POST and a www-url-encoded body
Summary
- Starting with a local HashMap object first as your in-memory storage lets you iterate more quickly over design concepts before adding a real database.
- We can use the Serde JSON library to parse external JSON files and map them onto our custom data types.
- Hash maps work great as in-memory storage solutions, but remember that the keys you use must implement the tree traits (PartialEq, Eq, and Hash) to be able to compare against each other.
- To be able to pass around state, we have to create a filter that returns a copy of the object we want to pass to more than one route handler.
- Each type of data you receive via HTTP can be parsed via filters in Warp, and you can use either json, query, param, or form from the framework.
- When adding more filters to extract data on our path, Warp automatically adds parameters in the function we are calling at the end.
- It is always helpful to create custom data types for each type of data we receive and parse from the HTTP body or from the path parameters.
- We have to implement traits on our custom errors to be able to return them via Warp.
- Warp includes HTTP status code types that we can use to return proper HTTP responses.
FAQ
What is the main goal of chapter 4 in the RESTful API project?
The chapter expands the Q&A service by adding the missing REST actions: creating, updating, and deleting questions, plus adding answers. It also introduces in-memory storage, shared application state, query parsing, and custom error handling.Why does the book start with an in-memory store instead of a real database?
An in-memory store is simpler for early development. It lets you quickly change data structures, test API behavior, and avoid database migrations until the application design stabilizes.Why is a HashMap used for storing questions?
A HashMap lets the application look up a question directly by ID instead of iterating through a list. That makes reads, updates, and deletes easier and more efficient.Why must QuestionId implement PartialEq, Eq, and Hash?
Because QuestionId is used as the key in a HashMap. Rust requires these traits so it can compare keys and compute hashes for lookups.How is shared state passed to Warp route handlers?
The store is wrapped in a Warp filter usingwarp::any().map(move || store.clone()). This allows each route handler to receive access to the shared state without taking ownership away from the server.Why are Arc and RwLock used around the store?
Arc allows the store to be shared across threads, and RwLock makes reads and writes safe in a concurrent async environment. This prevents data races while still allowing multiple readers and controlled writes.How are query parameters like start and end handled?
Warp’s query() filter extracts them into a HashMap<String, String>. The code then checks whether the parameters exist, parses them into numbers, and uses them for pagination.What problem do custom errors solve in this chapter?
Custom errors let the API return meaningful responses for cases like missing query parameters or failed parsing. The chapter defines anError enum and implements Display and Warp’s Reject trait so these errors can be handled cleanly.How does the POST route create a new question?
The POST route listens on/questions, accepts a JSON body, and passes both the shared store and the parsed Question into the handler. The handler then inserts the question into the store and returns a success response.How are PUT, DELETE, and form-encoded POST requests different in this chapter?
PUT updates an existing question using an ID from the URL and JSON from the body. DELETE removes a question by ID from the URL. The form-encoded POST route adds an answer usingapplication/x-www-form-urlencoded data parsed into a key-value map.
Rust Web Development ebook for free