http_helper 1.1.1
http_helper: ^1.1.1 copied to clipboard
The http_helper is a powerful yet easy-to-use HTTP networking library for Dart, designed to encapsulate the complexities of making HTTP requests in client applications.
http_helper #
The http_helper is a powerful yet easy-to-use HTTP networking library for Dart, designed to encapsulate the complexities of making HTTP requests in client applications.
This library provides a set of high-level API functions to send HTTP requests and receive responses. It wraps around the lower-level functionality of the http library, providing a simplified and more user-friendly interface for developers.
Key Features:
-
Simplified Request Methods: The package provides a simple way to send HTTP requests with any HTTP method (GET, POST, PUT, PATCH, DELETE).
-
HTTP Error Handling: The
http_helperis equipped with comprehensive error handling features to catch and handle HTTP errors effectively. -
Timeouts: The library includes built-in HTTP request timeout functionality to prevent requests from hanging indefinitely.
-
Callbacks/Middleware: It offers callback/middleware functions that can be set to handle different stages of an HTTP request.
-
Default Headers and Parameters: The library supports setting of default headers and parameters for HTTP requests, providing more convenience for developers who need to make many similar requests.
-
Flexible Response Handling: The library allows users to specify how to convert HTTP responses to their desired data format.
The http_helper is ideal for Dart developers who want to simplify their HTTP networking code while retaining full control over the request and response handling.
Whether you're building a large-scale client application, or you just need to make a few HTTP requests in a small project, the http_helper can help streamline your networking code and make your development process smoother and more efficient.
Examples: #
Example 1: GET Request with an object as response #
import 'package:http_helper/http_helper.dart';
import 'typicode_model.dart';
void main() async {
// Define the URL and path
String url = 'jsonplaceholder.typicode.com';
String path = '/posts/1';
// Make a GET request
var response = await HttpHelper.sendRequest<TypicodeModel>(
url,
path,
HttpRequestMethod.get,
(response) => TypicodeModel.fromJson(response),
);
print(response.statusCode);
// Print the response data
if (response.isSuccess) {
print(response.data.toString());
} else {
// Note: when `response.isSuccess` is false, `error` and `message` will never be null, so it is save to access them!
print(response.error!.message!);
}
}
Example 2: GET Request with a list of objects as response #
import 'package:http_helper/http_helper.dart';
import 'typicode_model.dart';
void main() async {
// Define the URL and path
String url = 'jsonplaceholder.typicode.com';
String path = '/posts';
// Make a GET request
var response = await HttpHelper.sendRequest<List<TypicodeModel>>(
url, path, HttpRequestMethod.get, (response) {
var responseList = response as List;
var mappedList = responseList
.map((e) => e == null
? null
: TypicodeModel.fromJson(e as Map<String, dynamic>))
.toList();
var withoutNulls =
List<TypicodeModel>.from(mappedList.where((e) => e != null));
return withoutNulls;
});
print(response.statusCode);
// Print the response data
if (response.isSuccess) {
print(response.data);
} else {
// Note: when `response.isSuccess` is false, `error` and `message` will never be null, so it is save to access them!
print(response.error!.message!);
}
}
Example 2: POST Request with Headers and Query Parameters #
import 'package:http_helper/http_helper.dart';
import 'typicode_model.dart';
void main() async {
// Define the URL, path, headers and query parameters
String url = 'jsonplaceholder.typicode.com';
String path = '/posts';
Map<String, String> headers = {"Authorization": "Bearer your_token_here"};
Map<String, dynamic> queryParams = {
"userId": 1,
"title": "Test Title",
"body": "Test Body"
};
// Make a POST request
var response = await HttpHelper.sendRequest<TypicodeModel>(url, path,
HttpRequestMethod.post, (response) => TypicodeModel.fromJson(response),
headers: headers, queryParameters: queryParams);
print(response.statusCode);
// Print the response data
if (response.isSuccess) {
print(response.data);
} else {
// Note: when `response.isSuccess` is false, `error` and `message` will never be null, so it is save to access them!
print(response.error!.message!);
}
}
Example 3: POST Request with Body #
import 'package:http_helper/http_helper.dart';
import 'typicode_model_example.dart';
void main() async {
// Define the URL, path, headers and query parameters
String url = 'jsonplaceholder.typicode.com';
String path = '/posts/1';
// Define the body
final body = """
{
"userId": 1,
"id": 101,
"title": "foo",
"body": "bar"
}
""";
// Make a POST request
var response = await HttpHelper.sendRequest<TypicodeModel>(
url,
path,
HttpRequestMethod.put,
(response) => TypicodeModel.fromJson(response),
body: body,
);
print(response.statusCode);
// Print the response data
if (response.isSuccess) {
print(response.data);
} else {
// Note: when `response.isSuccess` is false, `error` and `message` will never be null, so it is save to access them!
print(response.error!.message!);
}
}
Example 4: Using Callbacks/Middleware to handle different stages of an HTTP request #
import 'package:http_helper/http_helper.dart';
import 'typicode_model.dart';
void main() async {
HttpHelper.defaultHeaders = {"App-Language": "en"};
HttpHelper.timeoutDurationSeconds = 5;
HttpHelper.onBeforeSend = () {
// Perform any pre-send logic here
print("Request is about to be sent");
// Return an HttpError here if your pre-send logic determined that the request should not be sent
return null;
};
HttpHelper.onAfterSend = (GenericResponse response) {
print("Request has been sent, received response: ${response.statusCode}");
};
HttpHelper.onException = (Exception e) {
print("An exception occurred: ${e.toString()}");
};
HttpHelper.onTimeout = () {
print("Request timed out");
};
// Define the URL and path
String url = 'jsonplaceholder.typicode.com';
String path = '/posts';
// Make a GET request
var response = await HttpHelper.sendRequest<List<TypicodeModel>>(
url, path, HttpRequestMethod.get, (response) {
var responseList = response as List;
var mappedList = responseList
.map((e) => e == null
? null
: TypicodeModel.fromJson(e as Map<String, dynamic>))
.toList();
var withoutNulls =
List<TypicodeModel>.from(mappedList.where((e) => e != null));
return withoutNulls;
});
// Print the response data
if (response.isSuccess) {
print(response.data);
} else {
// Note: when `response.isSuccess` is false, `error` and `message` will never be null, so it is save to access them!
print(response.error!.message!);
}
}
Example 5: Using the middleware onBeforeSend to prevent users that are not logged in from entering the private area (fictional example) #
import 'package:http_helper/http_helper.dart';
import 'typicode_model.dart';
void main() async {
HttpHelper.onBeforeSend = () {
if (!user.loggedIn) {
// By returning an HttpError here, all 'sendRequest' calls will not send the request but will return this error if 'user.loggedIn' is false
return HttpError(
message: "You must be logged in to enter the private area",
)
}
return null;
};
// Define the URL and path
String url = 'accounts.example.com';
String path = '/private';
// Make a GET request
final response = await HttpHelper.sendRequest<UserPrivateDetails>(
url, path, HttpRequestMethod.get, (response) => UserPrivateDetails.fromJson(response),
);
// Print the response data
if (response.isSuccess) {
print(response.data);
} else {
// This will print the message defined in the HttpError above: 'You must be logged in to enter the private area'
print(response.error!.message!);
}
}