4 Implement a RESTful API

 

This chapter covers

  • Adding in-memory storage to our application
  • Passing around state to the route handlers
  • Reading from the in-memory storage across threads
  • Updating the in-memory 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 return them to the user. So far, we’ve implemented the GET route for /questions and return 404 when any other path or method is requested. This chapter will expand massively on this functionality. We continue to use our GitHub repository for this book (http://mng.bz/BZzJ).

We’ll add all missing HTTP methods (POST, PUT, and DELETE) and add the Answer type as well. Figure 4.1 gives an overview of which endpoints we plan to implement in this chapter.

Figure 4.1 We implemented the GET route for questions in chapter 3; this chapter covers POST, PUT, and DELETE, as well as adding comments via POST.
04-01

We will add in-memory storage, which will be replaced later in the book by a real database. Remember our code examples from chapter 2? We explained a simple asynchronous setup and talked about our runtime handing TCP connections over to different threads.

4.1 GET questions from in-memory

4.1.1 Setting up 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 in a thread-safe way

4.2.2 Adding a question

4.2.3 Updating a question