Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    What's Hot

    Flutter Interview Questions for freshers

    June 25, 2023

    Flutter Interview Questions for Experienced

    June 25, 2023

    Top 15 Flutter Interview Questions and Answers 2023

    April 22, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest YouTube
    DeepCrazyWorld
    Subscribe
    • Home
    • FLUTTER
      • UI
        • Splash Screen
        • Card Design
        • Login Screen
      • APPS
    • ANDROID
      • ANDROID APP
      • GAME APP
    • SOURCE CODE
    • ANDROID STUDIO
    • PROJECT
      • Android Projects
      • College Projects
      • Project Ideas
      • PHP Projects
      • Python Projects
    • MCQ
      • AKTU MCQ
        • RPA MCQ
        • COA MCQ
        • HPC MCQ
        • SPM MCQ
        • Renewable Energy All MCQ
        • Data Compression MCQ
        • Data Structure MCQ
        • Digital Image Processing MCQ
        • Software Engineering MCQ
        • Machine Learning MCQ
        • Artificial Intelligence MCQ
      • D PHARMA MCQ
        • Pharmaceutics – I MCQ
        • Pharmacognosy MCQ
        • Pharmaceutical Chemistry MCQ
        • Biochemistry and Clinical Pathology MCQ
        • Human Anatomy and Physiology MCQ
        • Heath Education and Community Pharmacy MCQ
      • COLLECTION
        • WORDPRESS
          • SEO
          • TOP 10 WORDPRESS THEME
        • PRODUCTIVITY
        • Networking
        • Program
        • YOUTUBE
        • QUOTES
    • INTERVIEW QUESTIONS
    DeepCrazyWorld
    Home»FLUTTER»Integrating an API into a Flutter – Working with REST APIs
    FLUTTER

    Integrating an API into a Flutter – Working with REST APIs

    DeepikaBy DeepikaMay 21, 2022Updated:May 21, 2022No Comments8 Mins Read
    Facebook Twitter LinkedIn WhatsApp Telegram
    Share
    Facebook Twitter LinkedIn Pinterest Telegram WhatsApp

    Integrating APIs in Flutter Application – Working with REST APIs – How can we integrate APIs into our app? Let’s find out!

    There are a lot of ways we show data in our app, such as:

    • Static data
    • From a file
    • From a database or public APIs

    The most common method is to show data from a database or public APIs. Even loading data from a database involves using APIs, though these can be private. So, let’s see how you can integrate APIs, fetch data from a public API, and use it in your Flutter app!

    Table of Contents

    • How do APIs Work?
    • Integrating an API into a Flutter app
      • Step 1: Get the API URL and endpoints
      • Step 2: Add relevant packages into the app (http, dio, chopper, etc.)
      • Step 3: Create a constant file that stores URLs and endpoints
    • Step 4: Create a model class to parse the JSON
    • Step 5: Create a file that handles the API call, and write specific methods to fetch and parse data
      • Step 6: Use the data in your app
    • Additional Reading
    • READ MORE

    How do APIs Work?

    A user application can make GET, POST, PUT, or DELETE HTTP requests to a database. In return, the database sends us data, results, or responses in the form of JSON, HTML, or XML (with the JSON format being the most widely used). We then parse the JSON into a proper model class and use it in our app.

    Integrating an API into a Flutter app

    There are a few steps that we can follow to easily integrate an API into our Flutter app:

    <img decoding=

    Step No. 1: Get the API URL and endpoints.

    Step No. 2: Add relevant packages into the app (http, dio, chopper, etc.).

    Step No. 3: Create a constant file that stores URLs and endpoints.

    Step No. 4: Create a model class to parse the JSON.

    Step No. 5: Create a file that handles the API call, and write specific methods to fetch and parse data.

    Step No. 6: Use the data in your app.

    In this article, we will use an example to learn how to integrate an API into a Flutter app. We will use the JSONPlaceholder API, which provides fake APIs, so that we can practice.

    So, let’s get to work!

    Step 1: Get the API URL and endpoints

    To get the API URL (referred to as the base URL) and endpoints, go to the JSONPlaceholder website. There, you will find the different APIs that they provide. Today, we’re going to use their users API. Hence, the base URL and API endpoint will be:

    Base URL: https://jsonplaceholder.deepcrazyworld.com

    API endpoint: /users

    The base URL for all APIs from a given database or API provider always remains the same; however, the endpoint changes depending on the API. Many API providers require you to obtain a private key (API key or access key), either by simply creating an account or by purchasing a key. The API key will be appended to the base URL. So, the new base URL will be:

    New base URL = BaseUrl/apiKey

    Step 2: Add relevant packages into the app (http, dio, chopper, etc.)

    There are many packages available on pub.dev that we can use to integrate APIs in Flutter. The most widely used packages are:

    • http
    • dio
    • chopper

    There are many more packages, though http is the most basic and easy to use. The other packages mostly act as wrappers for the http package and provide additional functionalities.

    Now, once you have created a new Flutter project, go to the pubspec.yaml file, and add the http package into it. Your pubspec.yaml file should look something like the following:

    name: rest_api_example
    description: A new Flutter project.
    publish_to: 'none' # Remove this line if you wish to publish to pub.dev
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.15.1 <3.0.0"
    
    dependencies:
      cupertino_icons: ^1.0.2
      flutter:
        sdk: flutter
      http: ^0.13.4
    
    dev_dependencies:
      flutter_lints: ^1.0.0
      flutter_test:
        sdk: flutter
    
    flutter:
      uses-material-design: true
    

    Step 3: Create a constant file that stores URLs and endpoints

    Now, it’s time to create a simple file named constants.dart that will hold all your URLs and endpoints. In our case, we only have one endpoint, but it’s a good practice to have a separate file. Your constants.dart file will look something like the following:

    class ApiConstants {
      static String baseUrl = 'https://jsonplaceholder.deepcrazyworld.com';
      static String usersEndpoint = '/users';
    }
    

    Here, we have created a class called ApiConstants and two static variables so that we can access them without creating an instance of the class like ApiConstants.baseUrl.

    Step 4: Create a model class to parse the JSON

    One way to access the data is by using the key directly. However, it’s an effective and easy approach to create a model class, parse the JSON, and get an object out of that JSON response.

    Use this to access the data directly:

    final data = json[0]['id'];
    

    Here, we try to access the ID of the 0th record of the JSON response. This is only easy to do when you have limited records and entries.

    Now, to create a model class, you will first need the entire JSON response you are getting from the API. To get that, just go to https://jsonplaceholder.typicode.com/users, and you will be able to obtain the entire JSON response, as this is a public API. In the case of a private API or custom back-end APIs, either it will be available in the documentation, or you can use Postman to hit the API and get the response.

    Once you have the response, you can create the model class using a simple method. Go to https://app.quicktype.io and paste the JSON response on the left side. In the options on the right side, select Dart, and your model class will be generated! You can then change the name of the class.

    Step 5: Create a file that handles the API call, and write specific methods to fetch and parse data

    Now, create a file called api_service.dart that will handle the API calls.

    import 'dart:developer';
    
    import 'package:http/http.dart' as http;
    import 'package:rest_api_example/constants.dart';
    import 'package:rest_api_example/model/user_model.dart';
    
    class ApiService {
      Future<List<UserModel>?> getUsers() async {
        try {
          var url = Uri.parse(ApiConstants.baseUrl + ApiConstants.usersEndpoint);
          var response = await http.get(url);
          if (response.statusCode == 200) {
            List<UserModel> _model = userModelFromJson(response.body);
            return _model;
          }
        } catch (e) {
          log(e.toString());
        }
      }
    }
    

    In the above file, we create a function called getUsers that returns a List. The first step is to hit the GET HTTP request. The next step is to check whether the API call was successful or not using response.statusCode. If the API call is successful, the statusCode will be 200. If the statusCode is 200, we then convert the JSON (response.body) into a List using the method userModelFromJson, which is available in the model class that we created, and then return the model object. in integrating APIs in Flutter app.

    Step 6: Use the data in your app

    We have created all the required files and methods for the API, which we can call from our app’s back end. Now it’s time to load this data on our UI. We don’t have to do much, just make a method call and load that result onto the UI.

    import 'package:flutter/material.dart';
    import 'package:rest_api_example/model/user_model.dart';
    import 'package:rest_api_example/services/api_service.dart';
    
    class Home extends StatefulWidget {
      const Home({Key? key}) : super(key: key);
    
      @override
      _HomeState createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
      late List<UserModel>? _userModel = [];
      @override
      void initState() {
        super.initState();
        _getData();
      }
    
      void _getData() async {
        _userModel = (await ApiService().getUsers())!;
        Future.delayed(const Duration(seconds: 1)).then((value) => setState(() {}));
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('REST API Example'),
          ),
          body: _userModel == null || _userModel!.isEmpty
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : ListView.builder(
                  itemCount: _userModel!.length,
                  itemBuilder: (context, index) {
                    return Card(
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(_userModel![index].id.toString()),
                              Text(_userModel![index].username),
                            ],
                          ),
                          const SizedBox(
                            height: 20.0,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            children: [
                              Text(_userModel![index].email),
                              Text(_userModel![index].website),
                            ],
                          ),
                        ],
                      ),
                    );
                  },
                ),
        );
      }
    }
    

    In the above code, we create an object of the type List. Then, in the initState, we call a method to get the data from our API. I have added Future. delayed in the method just so that we can simulate the API time response. integrating APIs in Flutter The API we are using is a fake one; hence, it’s pretty fast. However, real APIs aren’t that quick. So it becomes our duty to show a loader until the API response is available. Once the response is available, we rebuild the UI to show the data. Here, I have just shown a bit of data from the model class in integrating APIs in Flutter app.

    How to Setup Space Between Elements In Flutter 2023

    Additional Reading

    • SEO Practices Everyone Should Follow SEO Rules
    • Complete Top SEO Checklist
    • Top 50+ SEO Interview Questions
    • What is a Backlink? How to Get More Backlinks
    • TCS INTERVIEW QUESTIONS – CLICKE HERE
    • Top 20 Interview Program Questions
    • Android Projects with Source Code
    • Python Project With Source Code
    • Python Projects Ideas
    • Machine Learning MCQ Questions
    • Highest Paying Earning Website 
    • School Database Management System 
    • Top 20 Company Interview Questions

    READ MORE

    If you found this post useful, don’t forget to share this with your friends, and if you have any query feel free to comment it in the comment section.

    Thank you 🙂 Keep Learning !

    Share this…
    • Facebook
    • Pinterest
    • Twitter
    • Linkedin
    • Whatsapp
    • Gmail
    Post Views: 460
    api integration in flutter example flutter api call best practices flutter api call using provider flutter http get request with parameters flutter http request flutter rest api example github How do I access my API in flutter? How do I get data from REST API in flutter? How do I get my API key in flutter? post api in flutter What is API in flutter? what is rest api in flutter
    Share. Facebook Twitter LinkedIn WhatsApp Telegram
    Previous ArticleHow to Setup Space Between Elements In Flutter 2023
    Next Article Top ways to improve Google PageSpeed on WordPress
    Deepika
    • Website
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • LinkedIn

    Hey, I'm Deepika a professional blogger and Experienced in Android Developer,Flutter Developer, PHP Web Developer. Technically sound Post graduate pursuing M.Tech in Computer Science and Engineering. I Love to gain every type of knowledge that's why i have done many courses in different fields like engineering and technology. Skilled in Java, HTML, CSS,Bootstrap,j query PHP, Python, SQL, C, C++,Firebase,MySQL,SQLite,JavaScript. Also I have learned Networking.

    Related Posts

    Flutter Interview Questions for freshers

    June 25, 2023

    Flutter Interview Questions for Experienced

    June 25, 2023

    Top 15 Flutter Interview Questions and Answers 2023

    April 22, 2023

    The Best Flutter Stepper Widget : Build Multi-Step Forms

    April 22, 2023

    Leave A Reply Cancel Reply

    Our Picks
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    FLUTTER

    Flutter Interview Questions for freshers

    By DeepikaJune 25, 202303 Mins Read

    Certainly! Here’s a Flutter interview question along with its answer suitable for a fresher: Question:…

    Share this...
    • Facebook
    • Pinterest
    • Twitter
    • Linkedin
    • Whatsapp
    • Gmail

    Flutter Interview Questions for Experienced

    June 25, 2023

    Top 15 Flutter Interview Questions and Answers 2023

    April 22, 2023

    The Best Flutter Stepper Widget : Build Multi-Step Forms

    April 22, 2023
    Archives

    Subscribe to Updates

    Get the latest creative news from SmartMag about art & design.

    About Us
    About Us

    Hey, I'm Deepika a professional blogger and Experienced in Mobile App Developer ( Android and Flutter ) Technically sound Post graduated M.Tech in Computer Science and Engineering.
    I Love to gain every type of knowledge that's why i have done many courses in different fields like engineering and technology.

    Recent Posts
    • Flutter Interview Questions for freshers
    • Flutter Interview Questions for Experienced
    • Top 15 Flutter Interview Questions and Answers 2023
    • The Best Flutter Stepper Widget : Build Multi-Step Forms
    • Flutter ListView – A Guide to Creating Dynamic Lists with flutter
    • Top 10 Flutter Projects with source code For Startups
    • How to use chatGPT for UI/UX design with examples in 2023
    • Top 30 Flutter Interview Questions in 2023

    Flutter Interview Questions for freshers

    June 25, 2023

    Flutter Interview Questions for Experienced

    June 25, 2023

    Top 15 Flutter Interview Questions and Answers 2023

    April 22, 2023

    The Best Flutter Stepper Widget : Build Multi-Step Forms

    April 22, 2023
    Facebook Twitter Instagram Pinterest
    • Home
    • Contact Us
    • Disclaimer
    • Privacy Policy
    © 2023 DeepCrazyWorld. Designed by DeepCrazyWorld.

    Type above and press Enter to search. Press Esc to cancel.