Getting started with APIs using Flutter

Fetching data from an API using Flutter

Pranav Singhal
Nybles
7 min readAug 6, 2020

--

At some point in time in the lives of beginner developers, a puzzling question comes in their minds about how different applications retrieve data in real-time from the servers like the current weather data or simply the live cricket score data in just a matter of seconds. How is it done? The answer to this puzzle is by using this invisible unsung hero, the ‘API’ and it’s request/response Cycles! Excited huh? Give a go-to this 10 minutes read ahead and build your first Flutter App that retrieves live data from an API!

Flutter-Medium

So what is an API?

Boring Definition: An application programming interface (API) is a computing interface which defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc.~Wikipedia

Still, you wouldn’t have understood what’s an ‘API’ is😝. No worries, let’s understand it with an example from our daily lives.

Imagine that you(the client) are in a Restaurant. You want to order your favorite food. So the first step would be calling the waiter(API Call) and place your order(Request). Then the waiter would take your request to the kitchen(The Server) where your food(the Response) would be prepared. After the food(Response) is prepared you would receive it.

Now let’s replace these words to the domain of our discussion. You are the client in need of some data(say weather data) so you hit up the server(by making an API call) by specifying the city (Request) for which you want the weather data, then the server prepares your data and serves it to you in the form of JSON or XML format(Response). Sounds Simple now 😃? Let’s just dive in to see how to retrieve data in your Flutter App from an API.

Getting Started!

Open up your preferred code editor for dart coding like Visual Studio Code, Android Studio, etc. Let’s get productive, in this walkthrough, we would fetch the latest Covid-19 Global Statistics Summary from this free to use API: https://api.covid19api.com/summary

This is an HTTP API that returns data in JSON format. If you don’t know what JSON is then don’t worry. Let’s Visualise how data looks like in a JSON format. I recommend you to install the following extension on your Chrome Browser for better visualization of the JSON format:

After installing this extension open up the API URL on the browser and see to the data returned by this API link. You would see the data like this:

JSON IN FORM OF TREE
JSON IN FORM OF CHART

JSON format data is like a MAP from a key to a value. Think of the contents page of a book, You have a heading(the Key) and SubHeadings/Description (the Value) for this heading. Similarly, for the data above, we have a heading-Global that is associated with further Subheadings i.e. NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths, NewRecovered & TotalRecovered. Each of them further has a number(the Value) associated with them. In our App, we want to get the numbers associated with each heading to show them in our App.

First things First:

  1. As the data would be retrieved from the Internet, give Internet Permission to the App in AndroidManifest.xml file under android/app/src/main by writing the following under manifest:
AndroidManifest.xml

2. We are going to use the HTTP dart package, add the following dependency in the pubspec.yaml file under flutter:

pubspec.yaml

3. Go to your main.dart file and create a StateFull Widget as the state of the widget would change when the data would be received in the following code to create a basic UI to show the data we retrieved (make sure to import the http.dart package to be used ahead):

Basic Structure of the App

Retrieving data from the API

Let us create a function getData to receive the data from the API:

getData Function

The getData function is an async type of function as it is retrieving data from the server and it takes some time to do so. To make sure that the other functions in the main. dart file doesn’t have to wait for the completion of the getData function, we make it async. We have created a response type variable which receives the response from the API.’get’ is a function of HTTP package that calls the API & sends an API request to the server in the mentioned targeted URL as a parameter to the ‘get’ function. ‘await’ keyword is used with the ‘get’ function as it is the function that takes times to complete. To know more about async functions in dart check out it’s the documentation:

To know if we have successfully received the data from the API we are going to print the response body in the console. Now you have completed the initial setup. Now run the app on your phone or emulator and click on the Button to know if the data is printed on the console or not.

Console output on Pressing Get Data Button

Wow !! You have successfully retrieved data from an API and printed it on your console. Now our task is to decode this JSON format file and show the required information in the UI of the APP.

For decoding JSON response, we would use an inbuilt dart: convert library. First, we would create six int type variables to store the data to show in the UI. The following code illustrates the further working:

Completed getData function

Here, we can see that we are checking for the status code of the response. For a successful API response received, a status code=200 is sent over to us by the server. If something goes wrong then we would receive some other status code, to know more about status codes, check out the following:

So if nothing goes wrong, then we would receive a status code of 200 and would go further to decode the JSON format response and store the data in the respective variables. As we know, that JSON is in a key and value format, go back to the JSON Awesome viewer image:

Overview of what our API response looks like

Here we can see that there is a Key- “Global” and associated with it we have another dictionary with “NewConfirmed”, ”TotalConfirmed”, etc as the subkeys & each of those subkeys have a value that we have to decode & store in their respective variables. The format of decoding is shown in the above code snippet using the jsonDecode function which has a source and the keys as the parameters.

You simply just pass in the response.body as the source and the key- “Global” with the subkey- “NewConfirmed”. Please carefully spell out the name of the keys in this process, it should match with the API response.

So as we have successfully stored the data in the variables, let’s print it on the console to check if everything is right! Just run hot Restart the App and press the Get Data button.

Console Output

Yo! The data is successfully printed on the console. So we are ready to show the data in the UI of the APP. Just look over the complete code of the main.dart below that creates the UI to show the data retrieved from the API.

Completed Code:

Completed Code

See how our App finally looks like 😍😍:

Final App

You can also incorporate the Country Wise data from the API used above by using “Countries” as the key while decoding the JSON and then passing on the Country name as the subkey. Give it a try!

So this was just a basic walkthrough of what an API is and how to use it in our Flutter Apps. There are a lot of other things that we can do using APIs in flutter. To know more about them check out the following link:

About Me:

Hola, I am Pranav Singhal. I am an Undergraduate Student at IIIT-Allahabad. I am a member of the FOSS wing at GeekHaven, IIIT-Allahabad.

--

--