How to Get Data from REST API in Flutter

How to Get Data from REST API in Flutter

Get Data from REST API in Flutter – To facilitate interaction between disparate programs via the World Wide Web Transport Protocol (HTTP), REST APIs (Representational State Transfer) exist (Hypertext Transfer Protocol).

Get Data from REST API in Flutter from a server and present it locally. To send and receive HTTP requests to and from the REST API endpoints, you can use Flutter http package.

The basics of Get Data from REST API in Flutter are as follows:

  1. Use the http package to send an HTTP request to the REST API’s endpoint from json data.
  2. Please hold while we wait for the server’s response.
  3. The data you need can be parsed from the response.
  4. Make the information visible in the app.

The dio package makes HTTP requests simple and powerful, and the retrofit package provides a type-safe Flutter HTTP client.

Flutter http package provides a straightforward and efficient means of constructing HTTP requests, making it ideal for accessing data from REST APIs.

Get Data from REST API in Flutter.

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

Future<void> getData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    // do something with the data
  } else {
    throw Exception('Failed to load data');
  }
}

We send an http.get call to the REST API endpoint located at https://jsonplaceholder.typicode.com/posts using the http.get function. If the response’s status code is 200, we proceed to json.decode the response body to extract the information.

The information can then be flutter fetch data from api and display in listview using the data variable.

Full Code how to Get Data from REST API in Flutter and display it in a Flutter app:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter REST API Demo',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<dynamic> _data = [];

  Future<void> _getData() async {
    final response =
        await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
    if (response.statusCode == 200) {
      setState(() {
        _data = json.decode(response.body);
      });
    } else {
      throw Exception('Failed to load data');
    }
  }

  @override
  void initState() {
    super.initState();
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(children: [
          Image.asset(
            'assets/logo.png',
            height: 30,
          ),
          Text('flutterflux.com')
        ]),
      ),
      body: _data.isEmpty
          ? Center(child: CircularProgressIndicator())
          : ListView.builder(
              itemCount: _data.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Container(
                      color: Colors.blue, child: Text(_data[index]['title'])),
                  subtitle: Container(
                      color: Colors.amber, child: Text(_data[index]['body'])),
                );
              },
            ),
    );
  }
}

The information that was retrieved is kept in a HomePage widget, and that widget references the _data list. To access the endpoint of the REST API located at https://jsonplaceholder.typicode.com/posts, we send an http.get request using the http.get method. Then, if the response status code is 200, we update the _data list with the setState method after parsing the response body with json.decode.

Get Data from REST API in Flutter

The _data list is empty is checked in the build method of the HomePage widget. If no data is currently available, a CircularProgressIndicator widget will be displayed. If the list isn’t empty, we utilize the ListView.builder widget to put up a series of ListTile widgets that contain the retrieved information.

Get Data from REST API in Flutter with parameters

With the http package, you may retrieve data from a REST API in Flutter with query parameters. Example code for a GET request with parameters:

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

class ApiService {
  final String baseUrl = 'https://example.com/api';

  Future<dynamic> getData(String queryParam) async {
    final response = await http.get(Uri.parse('$baseUrl/data?param=$queryParam'));

    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception('Failed to fetch data from API');
    }
  }
}

In this code snippet, we start by defining an ApiService class with a baseUrl property. This is the base URL of the API endpoint from which we’ll be getting data. We also create a Get Data from REST API in Flutter method that takes a queryParam parameter as input.

Inside the getData method, we create the API endpoint URL by adding the queryParam parameter as a query string to the base URL using the http.get method from the http package. Then, we check to see if the API response has a status code of 200, which means it was successful. If it does, we decode the response body using the jsonDecode method from the dart:convert package and return it as a dynamic value. If the response status code isn’t 200, we throw an exception to show that the API call failed.

To use this ApiService class in your Flutter app, create an instance of it and call its getData method with the desired queryParam value. Example:

final apiService = ApiService();
final data = await apiService.getData('example');
print(data);

The following code, when executed, would request data from the API endpoint https://example.com/api/data?param=example and output the results to the console.

Conclusion

Flutter apps need REST API. Developers can dynamically extract data from web services using it. Flutter has various HTTP request and response packages. http, dio, etc.

Get Data from REST API in Flutter recommended practices include asynchronous programming, error handling, and pagination for big data sets. Security measures like HTTPS and authentication and authorization are crucial. read too How to Keep Screen Awake Using Wakelock in Flutter

Hello, I'm Cakra. I'm currently occupied with developing an application using the Flutter framework. Additionally, I'm also working on writing some articles related to it.

You May Also Like