API request in flutter: with real example in 2024

API request in Flutter

Written and reviewed by: 

SHARE

We will learn how to integrate APIs, fetch data from a public API, and apply it to our Flutter application in this article. This post is an excellent resource for learning how to use Flutter with REST APIs.

Table of Contents

What is an API request?

 

Application Programming Interface (API) requests are made to an API in order to obtain data or carry out an operation. In addition to offering more information than a website, APIs can handle data in a different way and with more complex queries than a website. An API, for instance, can automate specific operations, facilitate the integration of third-party data into corporate processes, allow various applications to communicate with one another, or give end users additional methods to access data.

An API request typically includes a URL, an HTTP method (GET, POST, PUT, PATCH, or DELETE), and request parameters. Request Parameters, or a Request Body, can be included in some HTTP Requests, and this is where a user will specify additional information that is associated with their request, such as the type of data that is requested.

As an example, suppose a user requests to view a catalog of items from an internet retailer. They could use the store’s API to do this by sending a GET request. The endpoint’s URL, the HTTP method (GET), and any pertinent parameters the user has given are all that would be included in this request. After that, the server would reply with the data that was requested.

In conclusion, an API request is a request made to an API in order to fetch data or carry out an operation. A URL, an HTTP method, and sometimes one or more request parameters are usually included.

Fundamentals of HTTP:

 

The ‘http’ library is available to developers for use when sending HTTP requests for your Flutter application. It is a future-based library.

You can do all operations, including GET, POST, PUT, DELETE, and so on, there.

This package contains a set of high-level classes and functions that simplify the process of accessing HTTP resources. It is cross-platform and compatible with PCs, mobile devices, and browsers.

Steps to integrate an API into the Flutter app:

The following are some simple steps we can take to incorporate an API into our Flutter application:

Step 1: Create your Flutter App

Step 2: You have to obtain the API URL and the endpoints.

Step 3: Include relevant packages (http, dio, etc.) in the pubspec.yaml file in your Flutter application.

Step 4: To parse the JSON, create a model class. You can also create a constant file to store the URL of the API.

Step 5: Write specialized methods to fetch and parse data, then create a file to handle the API call.

Step 6: Utilize the data in your app.

Let’s explore all the steps involved in creating a news app:

 
 

1. Create the Flutter app

 

Create the Flutter app by running the following command in the terminal:

				
					flutter create
				
			

Then run the app in your favorite emulator or physical devices.

2. Obtain the API URL:

 
As we are creating a news app, it has two URLs to fetch the data from the server. The first one is allNewsURL, and the second is breakingNewsURL.
 
				
					var allNewsurl =
      'https://newsapi.org/v2/everything?q=apple&from=2023-07-02&to=2023-07-02&sortBy=popularity&apiKey=17967ba13fcb47f881fcba918bd82b2a';
  var breakingNews =
      'https://newsapi.org/v2/top-headlines?country=us&apiKey=17967ba13fcb47f881fcba918bd82b2a';
				
			

Save it in any file or create a class and put it there.

3. Including relavent packages in the pubspec.yaml:

 
Add the package http in the dependency section of the pubspec.yaml. Try to add the latest version of the package.
 
				
					dependencies:
  http: ^1.2.1
				
			

4. Creating a model class to parse the JSON:

 

Create a new file called news_model.dart and create a new class in it. Firstly, we have to define some variables, which we can get from the API documentation. Go to the link, get the JSON file, and create this model class. You can do it very easily with the JSON to Dart Converter. It is available online.

				
					class NewsModel {
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;

  NewsModel(
      {this.source,
      this.author,
      this.title,
      this.description,
      this.url,
      this.urlToImage,
      this.publishedAt,
      this.content});

  NewsModel.fromJson(Map<String, dynamic> json) {
    source = json['source'] != null ? Source.fromJson(json['source']) : null;
    author = json['author'];
    title = json['title'];
    description = json['description'];
    url = json['url'];
    urlToImage = json['urlToImage'];
    publishedAt = json['publishedAt'];
    content = json['content'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (source != null) {
      data['source'] = source!.toJson();
    }
    data['author'] = author;
    data['title'] = title;
    data['description'] = description;
    data['url'] = url;
    data['urlToImage'] = urlToImage;
    data['publishedAt'] = publishedAt;
    data['content'] = content;
    return data;
  }
}

class Source {
  String? id;
  String? name;

  Source({this.id, this.name});

  Source.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['name'] = name;
    return data;
  }
}
				
			

5. Specialized methods to fetch and parse data:

 
To get allNews API from the server, create this method

				
					Future<List<NewsModel>> getallNews() async {
    try {
      var client = http.Client();
      var response = await client.get(Uri.parse(allNewsurl));
      if (response.statusCode == 200) {
        Map<String, dynamic> json = jsonDecode(response.body);
        List<dynamic> body = json['articles'];
        List<NewsModel> articleList =
            body.map((item) => NewsModel.fromJson(item)).toList();
        return articleList;
      } else {
        throw 'No News Found';
      }
    } catch (e) {
      throw 'Nothing Found';
    }
  }

				
			

To get breakingNews from the server, create this method:

				
					Future<List<NewsModel>> getBreakingNews() async {
    try {
      var client = http.Client();
      var response = await client.get(Uri.parse(breakingNews));
      if (response.statusCode == 200) {
        Map<String, dynamic> json = jsonDecode(response.body);
        List<dynamic> body = json['articles'];
        List<NewsModel> articleList =
            body.map((item) => NewsModel.fromJson(item)).toList();
        return articleList;
      } else {
        throw 'No News Found';
      }
    } catch (e) {
      throw 'Nothing Found';
    }
  }

				
			

6. Utilizing the data:

 

For using the data which we got from the server, we have to make a stateful widget class for showing the news data in our app:

This is the all news class:

				
					class AllNews extends StatefulWidget {
  const AllNews({super.key});

  @override
  State<AllNews> createState() => _AllNewsState();
}

class _AllNewsState extends State<AllNews> {
  ApiService apiService = ApiService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder(
            future: apiService.getallNews(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<NewsModel> articleList = snapshot.data ?? [];
                return ListView.builder(
                    physics: const BouncingScrollPhysics(),
                    itemCount: articleList.length,
                    itemBuilder: (context, index) {
                      return NewsItemList(newsModel: articleList[index]);
                    });
              }
              return const Center(
                child: CircularProgressIndicator(),
              );
            }));
  }
}
				
			

This is the breaking news class:

				
					class BreakingNews extends StatefulWidget {
  const BreakingNews({super.key});

  @override
  State<BreakingNews> createState() => _BreakingNewsState();
}

class _BreakingNewsState extends State<BreakingNews> {
  ApiService apiService = ApiService();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder(
            future: apiService.getBreakingNews(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<NewsModel> articleList = snapshot.data ?? [];
                return ListView.builder(
                    physics: const BouncingScrollPhysics(),
                    itemCount: articleList.length,
                    itemBuilder: (context, index) {
                      return NewsItemList(newsModel: articleList[index]);
                    });
              }
              return const Center(
                child: CircularProgressIndicator(),
              );
            }));
  }
}
				
			

By finishing all the steps above, we can create a simple news app by fetching the data from newsapi.org. Hopefully, we will learn the basics of API requests in Flutter.

Get the full code from the Github Repository

Check out Flutter Blog

FAQ

APIs allow Flutter applications to interact with external services and retrieve data, enabling features such as real-time updates, user authentication, and integration with third-party platforms.

HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. In Flutter, the http package enables developers to make HTTP requests to fetch data from APIs, making it essential for integrating external data sources into Flutter applications.

To integrate APIs into a Flutter app, you need to follow several steps, including obtaining the API URL, including relevant packages in the pubspec.yaml file, creating model classes to parse JSON data, writing specialized methods to fetch and parse data, and finally, utilizing the data in your app’s UI. TextButton, and more, or utilize specialized button packages for specific functionalities.

The newsmodel.dart file contains model classes that represent the structure of the data retrieved from the news API. These classes are used to parse JSON data into Dart objects, making it easier to work with the fetched data within the Flutter app.

Error handling is crucial when making API requests in Flutter. Developers can use try-catch blocks to handle exceptions that may occur during the HTTP request process. Additionally, they can utilize the FutureBuilder widget to display loading indicators or error messages based on the state of the asynchronous operation.

While it’s not mandatory, creating separate classes for different API endpoints can help organize your code and make it more modular. It allows for better separation of concerns and easier maintenance as your app grows.

You can test API integration in your Flutter app using unit tests, integration tests, or by running the app on various devices and simulators. Additionally, tools like Postman or Insomnia can be used to manually test API endpoints before integrating them into your app.

Yes, Flutter provides a rich set of widgets and tools for building custom UIs. You can use widgets like ListView, GridView, Card, Container, etc., to design visually appealing layouts to display the fetched data in your app according to your design requirements.

Written and reviewed by

Picture of Muhammad Naeem
Muhammad Naeem
Professional Flutter Developer
Scroll to Top