18 The time HTTP server

 

In this capstone, you will

Define partial functions and pattern matching constructs

Handle exceptions using a try-catch expression

Implement an HTTP server using http4s

In this lesson, you’ll adapt the code you wrote in the previous capstone to implement an HTTP server to provide the current date and time for a given country (e.g., “Italy” or “Japan”). In particular, you’ll expose and an HTTP API to return a representation of the current date and time, or a human-readable error message.

18.1 What time is it?

Let’s define an API that reflects the business requirements. Your server should be able to handle GET requests to the URI /datetime/<country> and return a string representing the current date and time in the correct time zone for the given country. For example, GET /datetime/italy should respond with a status code 200 – Ok and a string with the current date and time in Rome using a human-readable format, such as RFC 1123 (e.g., “Fri, 30 Apr 2021 11:44:35 +0200”). If the given country is not valid or not supported, your application should error with an explicative message. For example, GET /datetime/invalid should return a response with status code 404 - Not Found and the body "Unknown timezone for country invalid". Figure 18.1 provides a summary of the expected behavior of this API.

18.1.1 Setting your sbt project up

18.1.2 The TimePrinter class

18.1.3 The API routes

18.1.4 The HTTP server

18.1.5 Let’s try it out!

18.2 Possible improvements to our solution

Summary