What is REST API and how to fetch data with REST API in Flutter?

What is REST API and how to fetch data with REST API in Flutter?

Ayush Pawar
·Feb 24, 2022·

5 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Introduction
  • Project Setup
  • Coding the Logic
  • Conclusion

Introduction

Today, we will learn about how to use REST API in Flutter. REST API is a way to communicate between your frontend and database. The full form of API is Application Programming Interface. Suppose I have a database where I have stored a list of books. There are two ways to get the list of books from there.

The first is to write the query by yourself and get the data, the second is to call the API and the one who is handling the backend will write the query for fetching the data and will give the data back to you.

We will see how we can use REST API in Flutter to fetch some data.

Project Setup

First of all, let's set up our project. For that, in your pubspec file, add the HTTP package.

dependencies:
  http:

Now, in the main.dart file, Import the package.

import 'package:http/http.dart' as http;

We are using an alias called http here. The project setup is done. Let's start coding the logic.

Coding the Logic

We will break the whole process into 2 parts.

  1. Make the API call and get the data
  2. Convert it into Dart class and then render it on screen.

For step 1, we will need to create a function called as getData and add the following lines of code.

  void getData()async{

// http needs a URI datatype. So we use the URI.parse function which converts a string into a URI.
    Uri uri = Uri.parse("https://jsonplaceholder.typicode.com/todos/2");
// we store the data received from the API in a variable called response
    final response = await http.get(uri);
// we convert the body of the response in json and store it in a new variable.
    var jsonData = jsonDecode(response.body);
  }

The string in the Uri.parse() function is just a link that gives us mock data for testing. It is called a JSON placeholder. Here is thelink to the site..

I am using the easiest data because our topic is making HTTP requests and not parsing complex data. The data received from the above API looks something like this.

{
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
}

If you want to know what data a particular API is returning then use Postman for that. A postman is a tool through which we can visualize data coming from a request. If you don't want to use Postman then just add this extension to your browser. Now, in the new tab copy-paste the URL of the endpoint. You will be able to see the data in a structured manner. Something like this, Screenshot (125).png

It is recommended to use Postman because Rest API is not only about fetching data. There is a lot to it and postman makes life a lot easier when it comes to working with REST APIs.

With this, we complete step 1. Now onto step 2.

We will use this website to convert this JSON data into Dart classes. It is very easy. Just copy the above JSON data and paste it in the left column on the website. You will get the code for the Dart class on the right-hand side. Now just copy the whole code. In your lib folder, create a new file called todo_model.dart. In that, paste the whole code.

This is what your code will look like. If you are unable to generate the dart class, then copy-paste the code present below.

import 'dart:convert';

ToDo toDoFromJson(String str) => ToDo.fromJson(json.decode(str));

String toDoToJson(ToDo data) => json.encode(data.toJson());

class ToDo {
  ToDo({
    required this.userId,
    required this.id,
    required this.title,
    required this.completed,
  });

  int userId;
  int id;
  String title;
  bool completed;

  factory ToDo.fromJson(Map<String, dynamic> json) => ToDo(
    userId: json["userId"],
    id: json["id"],
    title: json["title"],
    completed: json["completed"],
  );

  Map<String, dynamic> toJson() => {
    "userId": userId,
    "id": id,
    "title": title,
    "completed": completed,
  };
}

In your main.dart, create a new variable called todo. We will store our model in this variable.

var todo;

Remember the getData function? Add this line of code in the function.

jsonData = jsonDecode(response.body);
setState(() {
// will convert the jsonData in a dart class. And we will store the whole model in variable todo.
 todo =  ToDo.fromJson(jsonData);
});

We are using setState because we are going to use this todo in our UI. So we need to update the widget where it is being used.

Let's work on the UI. First of all, create a TextButton. On pressing the button, we will call the getData function. The code for that will look like this.

TextButton(
 child: const Text("Get Data"),
 onPressed: (){
 getData();
   },
),

Now, we will create a new Text widget where we will show the title of our todo task. This widget will be just below our TextButton

Text(todo==null?"No data":todo.title.toString()),

We are doing a null check because when we start the app for the first time, the todo will be null. Data will be added in todo after we press the TextButton. So whenever todo is null we will show a text like "No Data".

Now, hot restart or stop and start the app. Initially, you will see a screen like this. Screenshot_20220223-181144.jpg

Now tap on the button and you will see some random data appear on the screen. This is your todo.title. Screenshot_20220223-181152.jpg

If you were able to recreate the two screens shown above then CONGRATULATIONS!! You have successfully learned to make an HTTP get request using Flutter.

Here is all the code that we used in this project.

// getData function
var todo;
void getData()async{
 Uri uri = Uri.parse("https://jsonplaceholder.typicode.com/todos/2");
 final response = await http.get(uri);
 var jsonData = jsonDecode(response.body);
 setState(() {
  todo =  ToDo.fromJson(jsonData);
  });
}
// our TextButton and Text Widget
Column(
 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.center,
 children: [
  TextButton(
   child: const Text("Get Data"),
   onPressed: ()async{
   getData();
  },
),
Text(todo==null?"No data":todo.title.toString()),
 ],
),

Conclusion

This was a very beginner-friendly guide to fetching data with REST API. Even the data that we fetched was very small and non-complex. Like GET, there is another method called POST where we can send data to a server. We will learn about that some other day.

If you were successful in fetching the to-do task then I would encourage you to go and try to fetch some more complex data from the same website. It will be a good practice exercise.

You can appreciate and support my blogs via. bmcoffee.png

Also, let's connect on Twitter. Follow CSwithIyush for more amazing tutorials, tips/tricks on Flutter & DSA.

Did you find this article valuable?

Support Ayush Pawar by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this