Integrating Flutter with APIs and external services

Raju Potharaju
GYTWorkz
Published in
5 min readFeb 23, 2023

Flutter is a popular framework for building mobile applications that can run on multiple platforms. To make your Flutter app more powerful, you may want to integrate it with APIs and external services.

In this blog, we will discuss how to integrate Flutter with APIs and external services, and I will provide some examples to help you get started.

What is an API?

API stands for Application Programming Interface. An API is a set of protocols and tools for building software applications. It allows two different software applications to communicate with each other. APIs can be used to integrate different systems or to share data between different applications.

If you want to more about API click here.

Why integrate Flutter with APIs and external services?

Integrating Flutter with APIs and external services can provide many benefits, such as:

  • Improved functionality: You can add more features to your app by integrating with external services and APIs.
  • Faster development: Integrating with APIs can save development time by allowing you to reuse existing functionality instead of building it from scratch.
  • Better user experience: Integrating with external services can improve the user experience by providing more personalized content and functionality.
  • Improved security: By integrating with secure APIs, you can ensure that your app and user data are protected.

How to integrate Flutter with APIs and external services?

Integrating Flutter with APIs and external services is relatively straightforward. Here are the general steps:

  1. Identify the APIs and external services you want to integrate with: Determine what APIs and external services your app needs to interact with to provide the desired functionality.
  2. Understand the API documentation: Understand the API documentation to determine what endpoints you need to use and what data you need to provide.
  3. Use a package to make API calls: There are many packages available for Flutter that can be used to make API calls, such as http, dio, and retrofit. Choose the package that best fits your needs.
  4. Parse the JSON response: APIs usually return data in JSON format, so you need to parse the JSON response to use the data in your app.
  5. Use the data in your app: Once you have the data from the API, you can use it in your app to provide the desired functionality.

Example 1: Integrating with OpenWeatherMap API

In this example, we will integrate with the OpenWeatherMap API to display the current weather for a given location.

  1. Identify the API: OpenWeatherMap provides a free API for accessing weather data.
  2. Understand the API documentation: The API documentation specifies that we need to make a GET request to the following endpoint to get the current weather for a given location: https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}. We need to provide the city name and our API key as parameters.
  3. Use the http package: We will use the http package to make the API call. Here is an example code snippet:
import 'dart:convert';
import 'package:http/http.dart' as http;

Future<WeatherData> fetchWeatherData(String cityName) async {
final response = await http.get(Uri.parse(
'https://api.openweathermap.org/data/2.5/weather?q=$cityName&appid={API key}'));
if (response.statusCode == 200) {
final jsonResponse = json.decode(response.body);
return WeatherData.fromJson(jsonResponse);
} else {
throw Exception('Failed to load weather data');
}
}
import 'package:intl/intl.dart';

class WeatherData {
final String cityName;
final double temperature;
final String sunrise;
final String sunset;

WeatherData({
required this.cityName,
required this.temperature,
required this.sunrise,
required this.sunset,
});

factory WeatherData.fromJson(Map<String, dynamic> json) {
final DateFormat formatter = DateFormat('dd MMM HH:mm');
return WeatherData(
cityName: json['name'],
temperature: (json['main']['temp'] - 273.15),
sunrise: formatter.format(
DateTime.fromMillisecondsSinceEpoch(json['sys']['sunrise'] * 1000)),
sunset: formatter.format(
DateTime.fromMillisecondsSinceEpoch(json['sys']['sunset'] * 1000)));
}
}
import 'package:flutter/material.dart';
import 'package:ui_app/api_services_blog/weather_model.dart';
import 'weather_api.dart';

class WeatherHome extends StatefulWidget {
const WeatherHome({super.key});
@override
State<WeatherHome> createState() => _WeatherHomeState();
}

class _WeatherHomeState extends State<WeatherHome> {
late String _cityName = '';
Future<WeatherData>? futureDate;

void getWeatherData() {
futureDate = fetchWeatherData(_cityName);
setState(() {});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Weather App'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
Container(
child: Column(
children: [
TextField(
onChanged: (value) => _cityName = value.trim(),
),
ElevatedButton(
onPressed: getWeatherData,
child: const Center(
child: Text("Submit"),
)),
],
)),
Container(
child: FutureBuilder<WeatherData>(
future: futureDate,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListTile(
leading: const Text('City Name'),
trailing: Text(snapshot.data!.cityName),
),
ListTile(
leading: const Text('Temperature'),
trailing: Text(
'${snapshot.data!.temperature.toStringAsFixed(1)} °C'),
),
ListTile(
leading: const Text('Sunrise'),
trailing: Text(snapshot.data!.sunrise.toString()),
),
ListTile(
leading: const Text('Sunset'),
trailing: Text(snapshot.data!.sunset.toString()),
),
],
);
} else if (snapshot.hasError) {
return const Text('Failed to load weather data');
}
return const CircularProgressIndicator();
},
))
],
),
),
);
}
}
Weather App

Example 2: Integrating with Firebase Authentication

In this example, we will integrate with Firebase Authentication to allow users to sign in to our app.

  1. Identify the external service: Firebase provides a set of services for building mobile and web applications, including Firebase Authentication.
  2. Understand the documentation: The Firebase Authentication documentation specifies that we need to configure Firebase in our app and use the provided API to authenticate users.
  3. Use the firebase_auth package: We will use the firebase_auth package to authenticate users. Here is an example code snippet:
import 'package:firebase_auth/firebase_auth.dart';

class Auth {
final FirebaseAuth _auth = FirebaseAuth.instance;

Future<UserCredential> signInWithEmailAndPassword(String email, String password) async {
try {
final UserCredential userCredential = await _auth.signInWithEmailAndPassword(
email: email,
password: password
);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
throw e;
}
}
}

4. Handle authentication errors: Firebase Authentication may return errors when authenticating users. We need to handle these errors and display appropriate messages to the user.

5. Use the authenticated user in your app: Once the user is authenticated, we can use their information in our app to provide personalised functionality.

Conclusion

Integrating Flutter with APIs and external services can provide many benefits, such as improved functionality, faster development, better user experience, and improved security. By following the general steps and using packages provided by the Flutter community, it is relatively straightforward to integrate Flutter with APIs and external services. The examples provided in this blog should help you get started.

If you find this blog informative do give a clap below and follow me.

Connect with me on LinkedIn for more flutter related content.

--

--

Raju Potharaju
GYTWorkz

Software Engineer with 3 years of experience building beautiful and complex Applications | Loves Teaching | Talks about Flutter, React, Python and Java