FAQ

*.chopper.dart not found ?

If you have this error, you probably forgot to run the build package. To do that, simply run the following command in your shell.
pub run build_runner build
It will generate the code that actually do the HTTP request (YOUR_FILE.chopper.dart). If you wish to update the code automatically when you change your definition run the watch command.
pub run build_runner watch

How to increase timeout ?

Connection timeout is very limited for now due to http package (see: dart-lang/http#21)
But if you are on VM or Flutter you can set the connectionTimeout you want
1
import 'package:http/io_client.dart' as http;
2
import 'dart:io';
3
​
4
final chopper = ChopperClient(
5
client: http.IOClient(
6
HttpClient()..connectionTimeout = const Duration(seconds: 60),
7
),
8
);
Copied!

Add query parameter to all requests

Possible using an interceptor.
1
final chopper = ChopperClient(
2
interceptors: [_addQuery],
3
);
4
​
5
Request _addQuery(Request req) {
6
final params = Map<String, dynamic>.from(req.parameters);
7
params['key'] = '123';
8
​
9
return req.copyWith(parameters: params);
10
}
Copied!

GZip converter example

You can use converters for modifying requests and responses. For example, to use GZip for post request you can write something like this:
1
Request compressRequest(Request request) {
2
request = applyHeader(request, 'Content-Encoding', 'gzip');
3
request = request.replace(body: gzip.encode(request.body));
4
return request;
5
}
6
...
7
​
8
@FactoryConverter(request: compressRequest)
9
@Post()
10
Future<Response> postRequest(@Body() Map<String, String> data);
Copied!

Runtime baseUrl change

You may need to change the base URL of your network calls during runtime, for example, if you have to use different servers or routes dynamically in your app in case of a "regular" or a "paid" user. You can store the current server base url in your SharedPreferences (encrypt/decrypt it if needed) and use it in an interceptor like this:
1
...
2
(Request request) async =>
3
SharedPreferences.containsKey('baseUrl')
4
? request.copyWith(
5
baseUrl: SharedPreferences.getString('baseUrl'))
6
: request
7
...
Copied!

Mock ChopperClient for testing

Chopper is built on top of http package.
So, one can just use the mocking API of the HTTP package. https://pub.dev/documentation/http/latest/testing/MockClient-class.html​
Also, you can follow this code by ozburo:
1
import 'dart:convert';
2
​
3
import 'package:chopper/chopper.dart';
4
import 'package:http/http.dart' as http;
5
import 'package:http/testing.dart';
6
​
7
part 'api_service.chopper.dart';
8
​
9
@ChopperApi()
10
abstract class ApiService extends ChopperService {
11
static ApiService create() {
12
final client = ChopperClient(
13
client: MockClient((request) async {
14
Map result = mockData[request.url.path]?.firstWhere((mockQueryParams) {
15
if (mockQueryParams['id'] == request.url.queryParameters['id']) return true;
16
return false;
17
}, orElse: () => null);
18
if (result == null) {
19
return http.Response(
20
json.encode({'error': "not found"}), 404);
21
}
22
return http.Response(json.encode(result), 200);
23
}),
24
baseUrl: 'https://mysite.com/api',
25
services: [
26
_$ApiService(),
27
],
28
converter: JsonConverter(),
29
errorConverter: JsonConverter(),
30
);
31
return _$ApiService(client);
32
}
33
​
34
@Get(path: "/get")
35
Future<Response> get(@Query() String url);
36
}
Copied!

Use Https certificate

Chopper is built on top of http package and you can override the inner http client.
1
import 'dart:io';
2
import 'package:http/io_client.dart' as http;
3
​
4
final ioc = new HttpClient();
5
ioc.findProxy = (url) => 'PROXY 192.168.0.102:9090';
6
ioc.badCertificateCallback = (X509Certificate cert, String host, int port)
7
=> true;
8
​
9
final chopper = ChopperClient(
10
client: http.IOClient(ioc),
11
);
Copied!

Authorized HTTP requests

Basically, the algorithm goes like this (credits to stewemetal):
Add the authentication token to the request (by "Authorization" header, for example) -> try the request -> if it fails use the refresh token to get a new auth token -> if that succeeds, save the auth token and retry the original request with it if the refresh token is not valid anymore, drop the session (and navigate to the login screen, for example)
Simple code example:
1
interceptors: [
2
// Auth Interceptor
3
(Request request) async => applyHeader(request, 'authorization',
4
SharedPrefs.localStorage.getString(tokenHeader),
5
override: false),
6
(Response response) async {
7
if (response?.statusCode == 401) {
8
SharedPrefs.localStorage.remove(tokenHeader);
9
// Navigate to some login page or just request new token
10
}
11
return response;
12
},
13
]
Copied!
The actual implementation of the algorithm above may vary based on how the backend API - more precisely the login and session handling - of your app looks like.