Implementing Rest API in Flutter (original) (raw)

Last Updated : 09 Apr, 2025

Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use APIs to display user data. We will use the http package, which provides advanced methods to perform operations. REST APIs use simple HTTP calls to communicate with JSON data because:

Let us see how a JSON file is used to fetch, delete, and update data in a Flutter app. We will create separate Dart files from main.dart for easier debugging and cleaner code in the following steps.

Steps to Implementing Rest API Application

Step 1: Setting up the Project

Install the http dependency and add it in pubspec.yaml file to use API in the application.

dependencies:
http:

Step 2: Creating a Request

This basic request uses the GET method to fetch data from the specified URL in JSON format. Each request returns a Future. A Future<> is used to represent a potential value or error that will be available at some time in the future. For example, if you request a server, the response will take a few seconds; this duration is represented by the Future<>. Here, we use the async and await features, which ensure that the response is handled asynchronously. This means that the code will not proceed until the response is received.

Future<List> fetchFruit() async {
final response = await http.get(url);
}
String url = "Your_URL";

**Note: You need to use your own **URL; we are not providing anything.

Step 3: Creating the Classes

Create a Fruit class & save asfruit.dart as shown below.

**fruit.dart:

Dart `

class Fruit { final int id; final String title; final String imgUrl; final int quantity;

Fruit( this.id, this.title, this.imgUrl, this.quantity, ); factory Fruit.fromMap(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } factory Fruit.fromJson(Map<String, dynamic> json) { return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']); } }

`

Step 4: Create Class Objects

Create the **FruitItem in fruitItem.dart.

**fruitItem.dart:

Dart `

import 'package:flutter/material.dart'; import 'fruit.dart';

class FruitItem extends StatelessWidget { FruitItem({required this.item});

final Fruit item;

@override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(2), height: 140, child: Card( elevation: 5, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Image.network( item.imgUrl, width: 200, errorBuilder: (context, error, stackTrace) {

            // Placeholder for error handling
            return Icon(Icons.error); 
          },
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.all(5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Text(
                  item.title,
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                Text("id: ${item.id}"),
                Text("quantity: ${item.quantity}"),
              ],
            ),
          ),
        ),
      ],
    ),
  ),
);

} }

`

Step 5: Create a List of Fruits

Create a FruitList class in fruitList.dart as shown below:

**fruitList.dart:

Dart `

import 'package:flutter/material.dart'; import 'fruit.dart'; import 'fruitItem.dart';

class FruitList extends StatelessWidget { final List items;

FruitList({Key key, this.items}); @override Widget build(BuildContext context) { return ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return FruitItem(item: items[index]); }, ); } }

`

Step 6: Displaying the Responses

Display the response on the screen fromthe ****main.dart file,**as shown below:

**main.dart:

Dart `

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

class MyHomePage extends StatelessWidget { final String title; final Future<List> products;

MyHomePage({Key key, this.title, this.products}) : super(key: key);

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Color(0xFF4CAF50), title: Text("GeeksForGeeks"), ), body: Center( child: FutureBuilder<List>( future: products, builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? FruitList(items: snapshot.data) : Center(child: CircularProgressIndicator()); }, ), )); } }

`

Following is the JSON Data upon running the application:

JSON Data

Following is the UI screen of the homepage of the Flutter application with decoded JSON data.

**Output:

fruit app

**Explanation of the above Program:

1. This statement is used to import the package as http.

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

2. This statement is used to convert the JSON data.

import 'dart:convert';

3. The following statement is used to handle the error code. If the response status code is 200, then we can display the requested data; otherwise, we can show an error message to the user. You can use any URL that accepts a get() request and returns a response in JSON format.

final response = await http.get('url');
if (response.statusCode == 200) {
//display UI}
else {
//Show Error Message
}
}

4. Following statements are used in order to decode the JSON data and display the output in a user-friendly manner. This ensures that it only accepts and extracts JSON data as per our requirements.

List decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map((json) => Fruit.fromMap(json)).toList();
}

Now that the REST API is successfully implemented in the Flutter app, follow these steps to update, delete, or send data using the JSON file, similar to the steps for creating a request. Since we need to send the noteID to the API, we must update the noteID and include it in the path using '/\$id' in the put(), delete(), or post() method. This is necessary to specify which note we are updating, deleting, or sending. Additionally, we need to re-fetch the notes after they are updated, deleted, or sent to display them.

1. **Updating the data

Dart `

Future updateFruit(String title) async { final http.Response response = await http.put( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{ 'title': title, }), );

if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to update album.'); } }

`

2. **Deleting the data

Dart `

Future deleteAlbum(int id) async { final http.Response response = await http.delete( 'url/$id', headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, );

if (response.statusCode == 200) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to delete album.'); } }

`

3. **Sending the data

Dart `

Future sendFruit(

String title, int id, String imgUrl, int quantity) async { final http.Response response = await http.post( 'url', headers: <String, String> { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String> { 'title': title, 'id': id.toString(), 'imgUrl': imgUrl, 'quantity': quantity.toString() }), ); if (response.statusCode == 201) { return Fruit.fromJson(json.decode(response.body)); } else { throw Exception('Failed to load album'); } }

`

How to Implement REST API in Flutter Application?