mirror of
https://github.com/aljazceru/Auto-GPT.git
synced 2026-01-01 21:34:27 +01:00
Add RestApiUtility Class for HTTP Requests
This commit introduces a new utility class, RestApiUtility, designed to encapsulate all the HTTP request operations. - Created RestApiUtility class with a constructor that accepts a base URL. - Added get method to perform GET requests and return data as a Map. - Added getList method to perform GET requests and return data as a List. - Added post method to perform POST requests with payload and return data as a Map. The class uses the http package for making network calls and dart:convert for JSON serialization and deserialization. This centralized approach makes it easier to manage API calls and handle errors across the application.
This commit is contained in:
40
lib/utils/rest_api_utility.dart
Normal file
40
lib/utils/rest_api_utility.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class RestApiUtility {
|
||||
final String baseUrl;
|
||||
|
||||
RestApiUtility(this.baseUrl);
|
||||
|
||||
Future<Map<String, dynamic>> get(String endpoint) async {
|
||||
final response = await http.get(Uri.parse('$baseUrl/$endpoint'));
|
||||
if (response.statusCode == 200) {
|
||||
return json.decode(response.body);
|
||||
} else {
|
||||
throw Exception('Failed to load data');
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<dynamic>> getList(String endpoint) async {
|
||||
final response = await http.get(Uri.parse('$baseUrl/$endpoint'));
|
||||
if (response.statusCode == 200) {
|
||||
return json.decode(response.body);
|
||||
} else {
|
||||
throw Exception('Failed to load data');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> post(
|
||||
String endpoint, Map<String, dynamic> payload) async {
|
||||
final response = await http.post(
|
||||
Uri.parse('$baseUrl/$endpoint'),
|
||||
body: json.encode(payload),
|
||||
headers: {"Content-Type": "application/json"},
|
||||
);
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
return json.decode(response.body);
|
||||
} else {
|
||||
throw Exception('Failed to post data');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user