Getting Started: Work with APIs in Flutter

Fetching data from JSONPlaceHolder — REST API

Bala Kowsalya
Kick-Starting: Flutter
5 min readMar 1, 2019

--

You might have wondered how we are getting data from worldwide in just a click of a button. For example, let’s take weather data, we access to weather data of any country from anywhere in just a matter of seconds. How is it? It’s all made possible because of the unsung heroes who are ‘APIs’ and it’s request/response cycle.

Courtesy of Flutterappdev

What is API?

In computer programming, an application programming interface (API) is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components. ~Wikipedia

Still, you wouldn’t have understood what is an ‘API’. No worries even I was struggling the same when I read about it for the first time. Then, I got a pretty much simpler explanation on API by MuleSoft videos on YouTube. The video explains about API in this way,

Consider a real-time scenario, in which you(client) are in a restaurant, yet to order your food. Whatever be the food you wish to have, first you need to call the waiter(API call) and place your order(request) and then it will be prepared in the kitchen(server) and served to you(response). And then, you get your delicious food(JSON or XML data)! Typical restaurant scene right? puzzling how this can be related to our discussion. 😂

Come on! Let’s replace the words, in our scenario, you are the client in the need of data and you hit the server with an API call and request for the data. The server will process this request and send back the response to you in JSON or XML format. That’s it. Super simple. Isn’t it?

How to fetch data from an API into a Flutter App?

For today we are going to see, how can we fetch the data from an API into a Flutter app.
Enough of talking, let’s start working.

Open your preferred IDE for writing Dart code. I’m using Visual Studio Code. We are going to get data from https://jsonplaceholder.typicode.com/posts/1 link, a sample post from the JSONPlaceholder and show the response in our app.

JSON data in https://jsonplaceholder.typicode.com/posts/1
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Getting Started!

  • Add http package:
    Firstly, we need to import the http package, which provides the simplest way to fetch data from the internet into our project.
    Update your pubspec.yaml file:
  • Request for data:
    The http.get() method is used to make a request to the specified ‘url’ and http.Response class contains the data received from a successful http call. We make this function of type Future because we will get the response for the request at some time in the future, not immediately.

In the above code, we are just making a network call. Not all the calls are made successful. So, how to check the status of the call?
It’s simple. Usually, the returning response will have information about the status of the request call, which can be accessed using response.statusCode.

Let’s tweak the code a little bit,

If the request call was successful, then yeah! we got the response and print ‘Status OK’ in Debug Console.

  • Convert the response into a Dart object:

1. Working with a raw Future<http.Response> is not very easy, so we need to convert it into a custom Dart object. Let’s first create a Post class which includes a factory method. A factorymethod is a constructor that creates a Dart object Post from JSON.

2. Convert the http.Response to a Post: We give our http response to fromJson factory method in Post class when our status of the request is successful.

  • Show the response in your UI:
    Just getting the response alone is not so useful, we are going to make this response data shown in our App UI by assigning it to any widget as it’s child attribute. You need to understand one of the important things we have used, FutureBuilder widget, because, as I said already, the data won’t be fetched immediately as soon as the app gets started. If we don’t make it Future, it will show error on calling with null values. To get rid of this error, we have used FutureBuilder, which has two attributes, future and builder. Now we show up the snapshot of data in our App by using snapshot.data.

— snapshot.hasData: To check whether we got the data.
— snapshot.hasError: To get an error message if it has any.
— snapshot.data.<key_name> — In our case, we display the value of ‘body’ key in that JSON data.

We are done now! We have written a code to make a request call, get the response and convert it into a Dart object and render it in our app UI. 🙌

But, wait it’s time for optimization!

It’s not recommended to put a call to an API in a build() method. Flutter calls the build() method often when it wants to change anything in the UI. If you leave the fetch call in your build() method, It will flood the API with unnecessary calls and slow down your app.
So, you need to hit the API only when needed. Move your calling statement to the fetchPost() function which in turn makes API call to outside your build() method.

In StatelessWidget,

In Stateful Widget, you can simply make a call only once using initState().

Now, we understood every snippet in our code. And the complete code is here!

Complete code

Complete code with StatefulWidget
While loading the data
Displaying the value of the key in response data

Just copy and paste it in your editor and run to see how it works.
Yaaaass! You got it. You have made an API call and got the response back.

If you would like to know how to make a Weather API call and parse the response to show the required data in your UI. No worries. I’m planning to write on that next.

If you find this tutorial useful, don’t forget to click/tap on the 👏 button as long as you can. :-) Follow to get more interesting tutorials on Flutter.
Would you like to appreciate my work? Buy Me A Cup Of Coffee! 😊

See other tutorials,

Happy Learning! ❤✔

--

--

Bala Kowsalya
Kick-Starting: Flutter

Passionate Computer Science Engineer. Curious. Technical Writer. Blogger. A Lifelong Learner. ❤ I wish to watch others learn things