Implementing Rest API in Flutter
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:
- It uses await & async features.
- It provides various methods.
- It provides class and HTTP to perform web requests.
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<Response>. 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<Fruit>> 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 as fruit.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: <Widget>[ 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<Fruit> 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 from the 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<Fruit>> 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<Fruit>>( 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:

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

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<Fruit> decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((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<Fruit> 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<Fruit> 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<Fruit> 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'); } }
Similar Reads
Flutter - Splitting App into Widgets Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and meth
5 min read
Flutter - Integrate Google Gemini API Currently, Artificial Intelligence is blooming all around. You must have heard about the ChatGPT, Bard and now Google has come up with a very new Artificial intelligence Gemini which responds to users in a truly human-like way. You can connect Google Gemini with Flutter in a very simple and quick wa
6 min read
HTTP GET Request in Flutter There is no use of building a UI in Flutter until you integrate it with your backend. A GET request is used to extract useful data from your backend to use it in your application.Steps to implement HTTP GET RequestStep 1 : Create a new Flutter ApplicationCreate a new Flutter application using the co
3 min read
Flutter - Sending Data To The Internet Interacting with the Internet is crucial for most apps to function. In Flutter, sending data to the internet is one of them, and the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. Steps to Implement Sending Data to the InternetStep 1
5 min read
Flutter - Make an HTTP POST Request In app development, the ability to fetch data from external sources, such as REST APIs, is a fundamental requirement. In Flutter, whether you need to send some data to the RESTful API, access a database, or then Send content from the Flutter App, Flutter provides you with the tools and packages(HTTP
5 min read