Flutter 3.41 is live! Check out theFlutter 3.41 blog post!
Make authenticated requests
How to fetch authorized data from a web service.
To fetch data from most web services, you need to provide authorization. There are many ways to do this, but perhaps the most common uses theAuthorization HTTP header.
Add authorization headers
# Thehttp package provides a convenient way to add headers to your requests. Alternatively, use theHttpHeaders class from thedart:io library.
finalresponse=awaithttp.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),// Send authorization headers to the backend.headers:{HttpHeaders.authorizationHeader:'Basic your_api_token_here'},);Complete example
#This example builds upon theFetching data from the internet recipe.
import'dart:async';import'dart:convert';import'dart:io';import'package:http/http.dart'ashttp;Future<Album>fetchAlbum()async{finalresponse=awaithttp.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),// Send authorization headers to the backend.headers:{HttpHeaders.authorizationHeader:'Basic your_api_token_here'},);finalresponseJson=jsonDecode(response.body)asMap<String,dynamic>;returnAlbum.fromJson(responseJson);}classAlbum{finalintuserId;finalintid;finalStringtitle;constAlbum({requiredthis.userId,requiredthis.id,requiredthis.title});factoryAlbum.fromJson(Map<String,dynamic>json){returnswitch(json){{'userId':intuserId,'id':intid,'title':Stringtitle}=>Album(userId:userId,id:id,title:title,),_=>throwconstFormatException('Failed to load album.'),};}}Unless stated otherwise, the documentation on this site reflects Flutter 3.38.6. Page last updated on 2025-02-12.View source orreport an issue.