In order to fetch data from many web services, you need to provideauthorization. There are many ways to do this, but perhaps the most commonuses the Authorization HTTP header.

Add Authorization Headers

The http package provides aconvenient way to add headers to your requests. You can also take advantage ofthe dart:io package for common HttpHeaders.

  1. Future<http.Response> fetchPost() {
  2. return http.get(
  3. 'https://jsonplaceholder.typicode.com/posts/1',
  4. // Send authorization headers to the backend
  5. headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"},
  6. );
  7. }

Complete example

This example builds upon the Fetching Data from theInternet recipe.

  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:http/http.dart' as http;
  5. Future<Post> fetchPost() async {
  6. final response = await http.get(
  7. 'https://jsonplaceholder.typicode.com/posts/1',
  8. headers: {HttpHeaders.authorizationHeader: "Basic your_api_token_here"},
  9. );
  10. final responseJson = json.decode(response.body);
  11. return Post.fromJson(responseJson);
  12. }
  13. class Post {
  14. final int userId;
  15. final int id;
  16. final String title;
  17. final String body;
  18. Post({this.userId, this.id, this.title, this.body});
  19. factory Post.fromJson(Map<String, dynamic> json) {
  20. return Post(
  21. userId: json['userId'],
  22. id: json['id'],
  23. title: json['title'],
  24. body: json['body'],
  25. );
  26. }
  27. }