Flutter- structure call API -GET

Tiempo de lectura: < 1 minuto

Reading Time: < 1 minute

The structure to make an API call and retrieve data in Flutter is as follows:

First, declare and initialize a variable with the API endpoint, in this case, I’ll call it `uri`:

final uri = 'https://example.com/api';

Next, declare the headers, specifically the `Content-Type`:

final headers = {
      'Content-Type': 'application/json',
  };

Then, make the API call and store the response in a variable, which I’ve named `response`:

final response = await http.get(Uri.parse(uri), headers: headers);

To check if the call was successful, I verify the `statusCode` and print the JSON response data to the console using the following code:

if (response.statusCode == 200) {
      print(json.decode(response.body));
} else {
      print('Request Error: ${response.statusCode}');
}

Here’s the complete code for the GET call:

Future<void> getApi() async {
    final uri = 'https://example.com/api';
    final headers = {
      'Content-Type': 'application/json',
    };
    final response = await http.get(Uri.parse(uri), headers: headers);
    if (response.statusCode == 200) {
      print(json.decode(response.body));
    } else {
      print('Request Error: ${response.statusCode}');
    }
}

Hope this helps! Have a great day.

Leave a Comment