Sub topic 6
Sending Headers and Authentication Tokens
Assume you know Dart classes, null safety, Future, async/await, and the http package. This chapter focuses on adding request metadata safely and choosing the correct authentication header.
What headers do
An HTTP header is a named value sent with a request or response. Headers describe the request, identify the client, or carry credentials. The request body contains resource data, while headers contain information about how to interpret or authorize that data.
Common headers include:
| Header | Purpose | Example |
|---|---|---|
| `Accept` | States the response format the client wants | `application/json` |
| `Content-Type` | States the request body format | `application/json` |
| `Authorization` | Carries an access credential | `Bearer eyJ...` |
| `X-API-Key` | Carries an API key when the service requires one | `abc123` |
Accept and Content-Type are different. A request can accept JSON without sending a body. A request with a JSON body should usually set Content-Type.
Adding an Authorization header
Many APIs use a bearer token. The word Bearer identifies the authentication scheme, followed by one space and the token.
import 'package:http/http.dart' as http;
class ApiClient {
ApiClient({
http.Client? client,
required this.accessToken,
}) : _client = client ?? http.Client();
final http.Client _client;
final String accessToken;
Future<http.Response> getProfile() {
final uri = Uri.https('api.example.com', '/v1/profile');
return _client.get(
uri,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer $accessToken',
},
);
}
void close() {
_client.close();
}
}The API server reads the Authorization header and checks the token. If the token is missing or invalid, the server commonly returns 401 Unauthorized. A valid token does not guarantee permission. The server can return 403 Forbidden when the identity is known but lacks access.
Keep tokens out of URLs, printed logs, error messages, and source control. HTTPS protects the request while it travels, but it does not protect a token accidentally written to a log. In a production app, store long-lived credentials using an appropriate secure storage solution rather than a plain preferences file.
API keys and other headers
Some services require an API key instead of a bearer token:
final response = await client.get(
Uri.https('api.example.com', '/v1/weather'),
headers: {
'Accept': 'application/json',
'X-API-Key': apiKey,
},
);Follow the API documentation exactly. Header names, prefixes, and credential placement are service-specific. Do not send every credential to every endpoint. A key intended for a public mobile client may identify the application, but it cannot keep a secret because users can inspect the app.
For JSON requests, combine authentication and content headers:
final response = await client.post(
Uri.https('api.example.com', '/v1/posts'),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken',
},
body: '{"title":"A new post"}',
);Token expiration
Access tokens often expire. Treat 401 as a signal that the token is unusable. If the application has a refresh-token flow, refresh the access token through a dedicated authentication service, then retry the original request once. Do not retry indefinitely. If refresh fails, clear the session and show a sign-in screen.
Exercise
Which status code usually means that a request lacks valid authentication, and which header commonly carries a bearer token?
Show answer
401 Unauthorized usually indicates missing or invalid authentication. The token commonly appears in Authorization: Bearer <token>.