Querying external APIs and consuming JSON
So far, we have learnt how to provide the user with a dummy JSON array of repositories in response to a request to /api/repos/:username
. In this section, we will replace the dummy data with the user's actual repositories, dowloaded from GitHub.
In Chapter 7, Web APIs, we learned how to query the GitHub API using Scala's Source.fromURL
method and scalaj-http
. It should come as no surprise that the Play framework implements its own library for interacting with external web services.
Let's edit the Api
controller to fetch information about a user's repositories from GitHub, rather than using dummy data. When called with a username as argument, the controller will:
- Send a GET request to the GitHub API for that user's repositories.
- Interpret the response, converting the body from a JSON object to a
List[Repo]
. - Convert from the
List[Repo]
to a JSON array, forming the response.
We start by giving the full code listing before explaining...