Serving JSON and HTML formats
Currently, if you take a look at the routes of our application, we have a root route that rendered base.leaf
. We also have two resourceful routes, /shopping_lists
and /items
, which serve JSON data. It would be great if we could respond with the HTML response when users request /shopping_lists
from the browser and serve JSON representation of our Shopping Lists when they go to the same /shopping_lists
endpoint, but now the request is made from the iOS app. Luckily, we can do this thanks to a powerful feature in Swift called Generics. To make this work, we would need to refactor our resourceful controllers. We also need to use a middleware, which will help us respond with the HTML and JSON responses based on who is making the request. For example, it will respond with an HTML response when a request is made from a browser; otherwise, it will respond with JSON. So, let's begin our refactoring by first creating a middleware.
Creating a middleware
You might be wondering...