Connecting to a web service and retrieving data with HTTP

Very few mobile apps are completely independent of external data: think of the apps you use for weather forecasts, listening to music, reading books, news, or emails. They all have something in common: they rely on data taken from an external source. The most common source to get data from a mobile (or any client) app is called a web service or web API.

What happens is that a client app connects to a web service, makes a request to get data, and if the request is legitimate, the web service responds by sending the data to the app, which then will parse the data for its features. The advantage of this approach is that developers only need to create and maintain one source of data and can have as many clients as needed. Actually this pattern (client/server) is nothing new, but it's extremely common when designing apps.

In the following, you can see a diagram showing this pattern. At the center, you have a remote server, which is the data source, and all around it are the clients, such as your mobile app, that connect to the server to retrieve data:

Web services generally expose data in two formats: JSON or XML. They are both text formats that can represent mostly the same kind of data, but as JSON is a bit more compact, it's a format you'll probably find more often when using web services.

In the following screenshot, you can see an example of each format:

In both formats, you can see an example of a movie, with the title, the year it was produced, the genre, and the actors. We don't need to get into the details of these formats; just note that both formats allow you to express complex data, and in Flutter, you can easily retrieve and parse both JSON and XML. The service we'll use in this chapter delivers JSON.

We won't deal with creating web services; we'll just use the one inside our app, but don't worry, you'll see how to create a server-side data source with Firebase in a later chapter.

In particular, we'll be using the Movie Database API (https://www.themoviedb.org). This is a community-built database with huge amounts of data that provides movies and TV information in several languages.

Before making your first connection to the database, you'll need to get an API key. You can obtain an API key by creating an account at https://www.themoviedb.org/, then clicking the API link in the bar on the left-hand side of your account page. This is free but requires a valid email to activate the account. Having an API key is also required to follow along with the examples in this chapter.

In the following sections, we'll create the app and retrieve the first set of data from the Movie Database web service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7