Making secure API calls is an essential part of building reliable Flutter applications. In this article, we’ll explore how to secure API calls using headers in Dart, such as Authorization
, Content-Type
, and custom headers. This is especially important when working with APIs that require authentication like Bearer tokens or API keys.
Why Secure Headers Matter
API headers provide an extra layer of protection. By embedding credentials and controlling access through headers, you prevent unauthorized users from misusing your endpoints.
Dependencies
Before proceeding, make sure you have the http
package in your pubspec.yaml
:
dependencies:
http: ^0.13.5
dependencies:
http: ^0.13.5
Run flutter pub get
to install it.
Sample Code to Secure API Call Using Headers
1. api_service.dart
– API Service Class
import 'package:http/http.dart' as http;
final String baseUrl = "https://example.com/api";
Future<http.Response> fetchSecureData(String token) async {
final url = Uri.parse("$baseUrl/data");
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Custom-Header': 'SecureAppHeader'
final response = await http.get(url, headers: headers);
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final String baseUrl = "https://example.com/api";
Future<http.Response> fetchSecureData(String token) async {
final url = Uri.parse("$baseUrl/data");
final headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Custom-Header': 'SecureAppHeader'
};
final response = await http.get(url, headers: headers);
return response;
}
}
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
final String baseUrl = "https://example.com/api";
Future<http.Response> fetchSecureData(String token) async {
final url = Uri.parse("$baseUrl/data");
final headers = {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Custom-Header': 'SecureAppHeader'
};
final response = await http.get(url, headers: headers);
return response;
}
}
2. main.dart
– Consuming the API
import 'package:flutter/material.dart';
import 'api_service.dart';
class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> {
const MyApp({super.key});
Widget build(BuildContext context) {
title: 'Secure API Example',
appBar: AppBar(title: const Text("Secure API Call")),
body: const Center(child: SecureApiWidget()),
class SecureApiWidget extends <a href="https://aliendro.id/statefulwidget-vs-statelesswidget-in-dart-guide/">StatefulWidget</a> {
const SecureApiWidget({super.key});
State<SecureApiWidget> createState() => _SecureApiWidgetState();
class _SecureApiWidgetState extends State<SecureApiWidget> {
String responseText = "Loading...";
ApiService apiService = ApiService();
String token = "your_token_here"; // Replace with your token
final response = await apiService.fetchSecureData(token);
if (response.statusCode == 200) {
responseText = response.body;
responseText = "Error: ${response.statusCode}";
Widget build(BuildContext context) {
return Text(responseText);
import 'package:flutter/material.dart';
import 'api_service.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends <a href="https://aliendro.id/create-ui-with-statelesswidget-in-dart/">StatelessWidget</a> {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Secure API Example',
home: Scaffold(
appBar: AppBar(title: const Text("Secure API Call")),
body: const Center(child: SecureApiWidget()),
),
);
}
}
class SecureApiWidget extends <a href="https://aliendro.id/statefulwidget-vs-statelesswidget-in-dart-guide/">StatefulWidget</a> {
const SecureApiWidget({super.key});
@override
State<SecureApiWidget> createState() => _SecureApiWidgetState();
}
class _SecureApiWidgetState extends State<SecureApiWidget> {
String responseText = "Loading...";
@override
void initState() {
super.initState();
getData();
}
void getData() async {
ApiService apiService = ApiService();
String token = "your_token_here"; // Replace with your token
final response = await apiService.fetchSecureData(token);
setState(() {
if (response.statusCode == 200) {
responseText = response.body;
} else {
responseText = "Error: ${response.statusCode}";
}
});
}
@override
Widget build(BuildContext context) {
return Text(responseText);
}
}
import 'package:flutter/material.dart';
import 'api_service.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Secure API Example',
home: Scaffold(
appBar: AppBar(title: const Text("Secure API Call")),
body: const Center(child: SecureApiWidget()),
),
);
}
}
class SecureApiWidget extends StatefulWidget {
const SecureApiWidget({super.key});
@override
State<SecureApiWidget> createState() => _SecureApiWidgetState();
}
class _SecureApiWidgetState extends State<SecureApiWidget> {
String responseText = "Loading...";
@override
void initState() {
super.initState();
getData();
}
void getData() async {
ApiService apiService = ApiService();
String token = "your_token_here"; // Replace with your token
final response = await apiService.fetchSecureData(token);
setState(() {
if (response.statusCode == 200) {
responseText = response.body;
} else {
responseText = "Error: ${response.statusCode}";
}
});
}
@override
Widget build(BuildContext context) {
return Text(responseText);
}
}
Pro Tips for Securing Your Headers
- Avoid hardcoding sensitive tokens in code. Use flutter_secure_storage to store them securely.
- Always use HTTPS to encrypt your API requests.
By following these practices, your Dart applications will securely interact with backend APIs while keeping user data safe and reducing the risk of exploits.
Post Views: 22