REST APIs in Flutter

0

 


How do APIs Work?

A person utility can make GET, POST, PUT, or DELETE HTTP requests to a database. In return, the database sends us data, results, or responses in the structure of JSON, HTML, or XML (with the JSON structure being the most extensively used). We then parse the JSON into a suitable mannequin classification and use it in our app.

Integrating an API into a Flutter app

There are a few steps that we can observe to without difficulty combine an API into our Flutter app:

Step 1: Get the API URL and endpoints.

Step 2: Add applicable applications into the app (HTTP, dio, chopper, etc.).

Step 3: Create a consistent file that shops URLs and endpoints.

Step 4: Create a model classification to parse the JSON.

Step 5: Create a file that handles the API call, and write unique techniques to fetch and parse data.

Step 6: Use the facts in your app.

In this article, we will use an instance to research how to combine an API into a Flutter app. We will use the  API, which presents pretend APIs so that we can practice. 

Step 1:

To get the API URL (referred to as the base URL) and endpoints, go to the website. There, you will discover the unique APIs that they provide. Today, we’re going to use their customer's API. Hence, the base URL and API endpoint will be: 


The base URL for all APIs from a given database or API company usually remains the same; however, the endpoint modifications rely on the API. Many API vendors require you to attain a personal key (API key or get entry to key), both via surely growing an account or by using buying 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:

There are many applications accessible on that we can use to combine APIs in Flutter. The most broadly used programs are:





There are many extra packages, although HTTP is the primary and effortless to use. The different programs generally act as wrappers for the HTTP package deal and grant extra functionalities.

Now, as soon as you have created a new Flutter project, go to the pubspec.yaml file, and add the HTTP bundle into it. Your pubspec.yaml file has to appear 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:

Now, it’s time to create an easy file named constants.dart that will maintain all your URLs and endpoints. In our case, we solely have one endpoint, however, it’s a true exercise to have a separate file. Your constants.dart file will seem something like the following:


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


Here, we have created a category referred to as ApiConstants and two static variables so that we can get admission to them except growing an occasion of the type like ApiConstants.baseUrl. 



Step 4:

One way to get the right of entry to the statistics is by using the use of the key directly. However, it’s a superb and effortless method to create a mannequin class, parse the JSON, and get an object out of that JSON response.

Use this to get the right of entry to the records without delay 

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


Here, we attempt to get entry to the ID of the 0th file of the JSON response. This is solely convenient to do when you have restricted archives and entries.

Now, to create a mannequin class, you will first want the complete JSON response you are getting from the API. To get that, simply go tohttps://jsonplaceholder.typicode.com/users, and you will be in a position to reap the complete JSON response, as this is a public API. In the case of a personal API or customized back-end APIs, both will be reachable in the documentation, or you can use https://www.postman.com/ to hit the API and get the response.

Once you have the response, you can create the mannequin type with the use of an easy method. Go to
https://app.quicktype.io/ and paste the JSON response on the left side. In the choices on the proper side, pick out Dart, and your mannequin classification will be generated! You can then trade the identity of the class. 

Step 5:

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 feature known as getUsers that returns a List. The first step is to hit the GET HTTP request. The subsequent step is to test whether or not the API name used to be profitable or no longer the usage of response.statusCode. If the API name is successful, the status code will be 200. If the status code is 200, we then convert the JSON (response. body) into a List the use of the approach userModelFromJson, which is on hand in the mannequin type that we created, and then return the mannequin object. 

Step 6:

We have created all the required documents and techniques for the API, which we can name from our app’s returned end. Now it’s time to load this fact on our UI. We don’t have to do much, simply make an approach name and load that end 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 kind List. Then, in the initState, we name a technique to get the records from our API. I have brought Future.delayed in the technique simply so that we can simulate the API time response. The API we are the usage of is a faux one; hence, it’s particularly fast. However, actual APIs aren’t that quick. So it turns into our responsibility to exhibit a loader till the API response is available. Once the response is available, we rebuild the UI to exhibit the data. Here, I have simply proven a bit of information from the mannequin class. 

Post a Comment

0Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !