chapter four

4 Implement a RESTful API

 

This chapter covers:

  • Adding a local storage to our application.
  • Passing around state to the route handlers.
  • Reading from the local storage across threads.
  • Updating the local storage in a thread-safe manner.
  • Parsing data out of JSON and url-form bodies.
  • Extracting information out of query parameters.
  • Adding custom errors to our application.

In the previous chapter, we started building our Q&A web service. We created our first custom types - Question and QuestionId - and started to handle error cases and returned them to the user.  So far, we implemented the GET route for /questions and return 404 when any other path or method is requested. This chapter will expand massively on the functionality. We continue to use our GitHub repository for this book (https://github.com/Rust-Web-Development/code/tree/main/ch_04).

Description: Text Description automatically generated

Figure 4.1: We implemented the GET route for questions in chapter 3; this chapter will cover POST, PUT and DELETE, as well as adding comments via POST.

We will add a local storage, which will be replaced later in the book by a real database. We add all missing HTTP methods (POST, PUT and DELETE) and add the Answer type as well. Remember our code examples from chapter 2? We explained a simple asynchronous setup and talked about that our runtime is handing TCP connections over to different threads.

4.1 GET questions from “in-memory”

4.1.1 Setup a mock database

4.1.2 Preparing a set of test data

4.1.3 Reading from the fake database

4.1.4 Parsing query parameters

4.1.5 Returning custom errors

4.2 POST, PUT and DELETE questions

4.2.1 Updating our data thread-safely

4.2.2 Adding a question

4.2.3 Updating a question

4.2.4 Handling malformatted requests

4.2.5 Remove questions from the storage

4.3 POST answers via url-form-encoded

4.3.1 Difference between url-form-encoded and JSON

4.3.2 Adding answers via url-form-encoded

4.4 Summary