4

I tried using http package of flutter and create a custom client with headers.

Code

class ApiClient extends http.BaseClient {
  final http.Client _inner;
  
  ApiClient(this._inner);

  _setHeaders() => {
    'Content-type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer token here...'
  };

  Future<http.StreamedResponse> send(http.BaseRequest request) {
    request.headers.addAll(_setHeaders());
    return _inner.send(request);
  }
}

How can I add a base URL to my custom client?

1
  • 1
    did you find a solution?
    – DNS
    Commented Aug 30, 2021 at 8:07

2 Answers 2

1

Since ApiClient inherits http.BaseClient, you should be able to have access to other methods as well. Simply access the method on your ApiClient for example.

var baseUrl = Uri.parse('https://example.com/');
var response = await ApiClient.post(baseUrl);
0

I use a similar approach on my projects:

class ApiClient extends http.BaseClient {
  final http.Client _inner;
  final String baseUrl;
  
  ApiClient(this._inner, this.baseUrl);

  Uri url(String path, [Map<String, String?>? queryParameters]) {
    return Uri.parse('$baseUrl$path').replace(queryParameters: queryParameters);
  }

  // other methods ...
}

Usage sample:


final api = ApiClient(inner, 'https://testhost/api/v1');
final response = await api.post(api.url('/test', {'q': 'a'}));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.