Files
recipe-app/flutter/lib/core/api/api_client.dart
T

37 lines
1.3 KiB
Dart

import 'package:http/http.dart' as http;
/// Platform-neutral HTTP client.
/// API base URL is injected at build time via --dart-define=API_BASE_URL.
/// Default is same-origin '/api' to avoid mixed-content on HTTPS sites.
class ApiClient {
final String baseUrl;
final http.Client _client;
ApiClient({http.Client? client})
: baseUrl = const String.fromEnvironment(
'API_BASE_URL',
defaultValue: '/api',
),
_client = client ?? http.Client();
Map<String, String> _headers({String? token}) => {
'Content-Type': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
};
Future<http.Response> get(String path, {String? token}) =>
_client.get(Uri.parse('$baseUrl$path'), headers: _headers(token: token));
Future<http.Response> post(String path, String body, {String? token}) =>
_client.post(Uri.parse('$baseUrl$path'),
headers: _headers(token: token), body: body);
Future<http.Response> put(String path, String body, {String? token}) =>
_client.put(Uri.parse('$baseUrl$path'),
headers: _headers(token: token), body: body);
Future<http.Response> delete(String path, {String? token}) =>
_client.delete(Uri.parse('$baseUrl$path'),
headers: _headers(token: token));
}