Flutter API Integration with http – A Beginner's Guide
In Flutter, APIs allow your app to communicate with web services — such as fetching user data, posting forms, or connecting to any backend. In this tutorial, we’ll learn how to integrate REST APIs in Flutter using the http package, in a way that’s simple, clear, and production-ready.
What is an API?
An API (Application Programming Interface) is a way for your app to communicate with a backend server. It lets your app send and receive data.
for eg:
=> Your app asks: “Hey server, give me a list of users.”
=> The server replies with data like:
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
]=> look at the free api given below, copy and paste it to your browser and see the result :
https://jsonplaceholder.typicode.com/usersreturns a list of fake users in JSON format. We can display that data in our Flutter app.
That’s a GET request. You can also use POST to send data, PUT to update, and DELETE to remove items.
Before Moving into the project make a project structure:
lib/
├── user_model.dart
├── api_service.dart
└── user_list_screen.dartStep 1: Add http Package
Flutter doesn’t come with built-in tools for making HTTP requests, so we use the http package.
Open Your Terminal and run
flutter pub add httpLearn More : https://pub.dev/packages/http
Step 2: Create a User Model
APIs return data in JSON format (i.e., a structured string of key-value pairs). We convert that JSON into Dart objects using a model class.
Get Flutter_Waves’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s an example JSON from the API:
{
"id": 1,
"name": "Leanne Graham",
"email": "Sincere@april.biz"
}First, we need a model class to parse the JSON response from the API into Dart objects:
class User {
final int id;
final String name;
final String email;
User({required this.id, required this.name, required this.email});
// Converts JSON map to User object
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
}factory User.fromJson(...)is a constructor that creates aUserfrom a map (parsed JSON).requiredensures null-safety, so all fields must be provided.
Step 3: Write an API Service
This is a class responsible for sending requests and returning parsed data.
Let’s build a service class that uses the http package to fetch users:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'user_model.dart';
class ApiService {
final String url = 'https://jsonplaceholder.typicode.com/users';
Future<List<User>> fetchUsers() async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// Convert JSON response to List<dynamic>
List<dynamic> body = jsonDecode(response.body);
// Map each item to a User object
List<User> users = body.map((e) => User.fromJson(e)).toList();
return users;
} else {
throw Exception('Failed to load users');
}
}
}http.get(Uri.parse(url)): Sends a GET request to the URL.jsonDecode(response.body): Converts JSON string into a Dart object.List<dynamic>: Represents the JSON array of users..map((e) => User.fromJson(e)).toList(): Converts each JSON map to aUser
Step 4: Display API Data in the UI
This is a class responsible for sending requests and returning parsed data.
Let’s now use FutureBuilder to display the fetched data in a widget:
import 'package:flutter/material.dart';
import 'user_model.dart';
import 'api_service.dart';
class UserListScreen extends StatefulWidget {
@override
_UserListScreenState createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
late Future<List<User>> futureUsers;
@override
void initState() {
super.initState();
futureUsers = ApiService().fetchUsers(); // fetch data once on start
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Users')),
body: FutureBuilder<List<User>>(
future: futureUsers,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.hasError)
return Center(child: Text('Error: ${snapshot.error}'));
else if (!snapshot.hasData || snapshot.data!.isEmpty)
return Center(child: Text('No users found.'));
else {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (_, index) {
final user = snapshot.data![index];
return ListTile(
title: Text(user.name),
subtitle: Text(user.email),
);
},
);
}
},
),
);
}
}What We Have Learnt
=> Add and use the http package
=> Fetch data from a REST API
=> Convert JSON to Dart models
=> Display it with FutureBuilder






