Hello. In today's post I'll explain how to fetch data using a REST API with Flutter.
What is REST
REST is a software architecture used for communication between web-based applications, and it is based on the HTTP protocol.
REST API
A REST API is an interface that any application can use to communicate with other applications. They work over the HTTP protocol using requests and responses. Through REST APIs, requests such as Get, Post, Put and Delete let us perform read, update and delete operations.
Flutter — REST API
If we want to use an API in our apps, adding the http package available here to our project will make our job much easier.
As an example, I'll use a football API. I'll use the API available here. In my project I create a class named FootballAPI and define an async function named getAllLeaugeData inside it.
import 'package:http/http.dart' as http;
final response = await http.get(
Uri.parse('https://football98.p.rapidapi.com/competitions'),
headers: {
'X-RapidAPI-Key': apiKey,
'X-RapidAPI-Host': 'football98.p.rapidapi.com'
});
String jsonString = json.decode(response.body);
print(jsonString);We'll send an http request to the API. We'll assign the result to a variable I named response. I create my request by writing await http.get().
We need to put a Uri and headers inside the get method. So where do we get these from?
const options = {
method: 'GET',
url: 'https://football98.p.rapidapi.com/competitions',
headers: {
'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
'X-RapidAPI-Host': 'football98.p.rapidapi.com'
}
};When we look at the API, there are headers and a url here. We also need to put a Uri and headers into our http.get() method. The headers we'll use are the ones found in the API documentation.
The url in the documentation is a string. But we need to use a Uri. We take the url value here and put it inside the get() method as Uri.parse(url).
Uri.parse ensures the URL is converted and processed correctly, and it takes a string expression.
Fetching data is basically this simple. However, there are a few cases we need to check.
Did we fetch the data correctly? To understand this we need to look at the statusCode value. We had assigned the http.get() operation to a variable named response. By writing response.statusCode we can tell whether the operation succeeded. If our statusCode returns 200, we can tell that we received a correct response from the API.
How will we display the data? Usually the data returned by an API is in JSON format. We know we assigned the value from the API to our response variable. We can also verify success with the statusCode. To display the data, we write json.decode(response.body) to make the body value inside response usable.
I tried to explain fetching data using an API with Flutter as best I could. For now we only displayed it in the console. In my next post I'll explain how we can use this data in our app with FutureBuilder.
You can find the source code here. Thanks for reading. Happy coding, everyone.