Working with REST APIs — Flutter💙

Abhishek Doshi
Google Developer Experts
6 min readMar 2, 2022

--

Data, data and data. Everywhere we see in today’s world is just data. So how can we get data in our app? How can we integrate APIs in our app? Let’s check it out!

We have a lot of ways to show data in our app:

  • Static Data
  • From a file

And another form is from a database or public APIs.

The most popularly used form is from Database or Public APIs. Even when you want to load data from the database, you will have APIs but they can be private. So, let’s see how you can integrate, fetch data from a public API and use it in your flutter app!

How do APIs Work?

A user application can contact any database through HTTP requests. So, we can create GET, POST, PUT, or DELETE HTTP requests to a database. In return, the database sends us data or results or responses in form of JSON or HTML or XML. The JSON format is widely used. We then parse the JSON into a proper model class and use it in our app.

Integrate APIs into Flutter App

To integrate an API, we have a few steps that we can follow for our ease:

Step 1: Get API URL and endpoints.

Step 2: Add relevant packages into the app (http, dio, chopper, etc.).

Step 3: Create a constant file that stores URLs and endpoints.

Step 4: Create a model class to parse the JSON.

Step 5: Create a file that handles the API call and write specific methods to fetch data and parse it.

Step 6: Use the data in your app.

In this article, we will learn with an example. We will use JSONPlaceholder API which provides fake APIs for us to practice.

So, let’s get to work then!

Step 1: Get API URL and endpoints.

To get the API URL (referred to as base URL) and endpoints, go to the JSONPlaceholder website and you will find different APIs that they provide. We would today use the users API that they have. Hence,

Base URL: https://jsonplaceholder.typicode.com
API Endpoint: /users

When you have a database or API provider, the base URL for all APIs remain the same however the endpoint changes depending on the API. In many API Providers, you will have to obtain a private key (API Key or Access Key) either by simply creating an account or it can be a paid one. That API Key will be just appended to the base URL. So the new base URL will be:

New Base URL = BaseUrl/apiKey

Example: https://jsonplaceholder.typicode.com/abcdefghijklmnopqrxyz

Step 2: Add relevant packages into the app (http, dio, chopper, etc.)

There are many packages available in pub.dev that we can use to integrate APIs in Flutter. The most widely used packages are:

And many more… However, http is the most basic and easy to use. The other packages are mostly the wrapper of the http package and provide additional functionalities.

Now, once you have created a new flutter project, go to pubspec.yaml file and add the http package into it. Your file should look something like the following:

Step 3: Create a constant file that stores URLs and endpoints.

Now, it’s time to create a simple file named constants.dart that will hold all your URLs and endpoints. In our case, we only have one endpoint, but it’s a good practice to have a separate file. Your file will look something like the following:

Here, we have created a class called ApiConstants and created 2 static variables so that we can access them without creating an instance of the class like ApiConstants.baseUrl .

Step 4: Create a model class to parse the JSON.

One way to access the data is directly using the key. However, it’s a good and easy approach to create a model class, parse the JSON and get an object out of that JSON response.

Access data directly:

final data = json[0]['id'];

In this, we tried to access the id of 0th record of the JSON response. This is easy only when you have limited records and entries.

Now, to create a model class, first, you will need the entire JSON response that you are getting from the API. To get that, just go to https://jsonplaceholder.typicode.com/users and you will be able to obtain the entire JSON response as this is a public API. Now, in the case of private API or custom backend APIs, either it will be available in the documentation or you can use Postman to hit the API and get the response.

Now, once you have the response, you can create the model class using a simple method. Go to https://app.quicktype.io and on the left side paste the JSON response. In the options on the right side, select Dart and your model class will be generated! You can then change the name of the class.

Your model class file will look something like the following:

Step 5: Create a file that handles the API call and write specific methods to fetch data and parse it.

Now, create a file called api_service.dart that will handle the API calls.

Now, in the above file, we have created a function called getUsers that returns List<UserModel> . The first step is to hit the GET HTTP request. The next step is to check, whether the API call was successful or not. That can be checked using response.statusCode . If the API call will be successful, statusCode will be 200. If the statusCode is 200, we then convert the JSON (response.body) into a List<UserModel> using the method userModelFromJson which is available in the model class that we created and then return the model object.

Step 6: Use the data in your app.

We have created all the required files and methods for the API, which we can call our app backend. Now it’s time to load this data on our UI. We won’t be doing much, just a method call and load that result in UI.

Now, in the above code, we created an object of List<UserModel> and then in the initState we called a method to get the data from our API. In the method, I have added Future.delayed , just so that we can simulate the API time response. This API that we are using is a fake one and hence it’s pretty fast. However, real APIs aren’t that fast. So it becomes our duty to show a loader until the API response is available. Once the response is available, we rebuild the UI to show the data. Here, I have just shown a few of the data from the model class.

Output:

Want to try it by yourself? Feel free to clone the GitHub Repository!

Originally published at CodeMagic Blog.

Hope you enjoyed this article!

If you loved it, you can Buy Me A Coffee!

Don’t forget to connect with me on:

Don’t stop, until you are breathing!💙
- Abhishek Doshi

--

--

Abhishek Doshi
Google Developer Experts

Google Developer Expert — Dart, Flutter & Firebase 💙💛