API constructor

API({
  1. required String hostUrl,
  2. required String ua,
  3. String? keyId,
  4. String? keySecret,
  5. String? oauthToken,
  6. Map<String, String>? headers = const {},
})

Implementation

API({
  required this.hostUrl,
  required this.ua,
  this.keyId,
  this.keySecret, // Made optional for OAuth scenarios
  this.oauthToken,
  this.headers = const {},
}) {
  // Allow either key_id/key_secret OR oauthToken
  if ((keyId == null || keySecret == null) && oauthToken == null) {
    throw ArgumentError(
      'Either (keyId, keySecret) or oauthToken is mandatory',
    );
  }

  final authHeaders = <String, dynamic>{};
  if (keyId != null && keySecret != null) {
    final credentials = '$keyId:$keySecret';
    final encodedCredentials = base64Encode(utf8.encode(credentials));
    authHeaders['Authorization'] = 'Basic $encodedCredentials';
  } else if (oauthToken != null) {
    authHeaders['Authorization'] = 'Bearer $oauthToken';
  }

  client = Dio(
    BaseOptions(
      baseUrl: hostUrl,
      headers: {
        'User-Agent': ua,
        ...getValidHeaders(headers),
        ...authHeaders, // Add authentication headers
      },
    ),
  );
}