Initial commit
This commit is contained in:
78
lib/services/apiService.dart
Normal file
78
lib/services/apiService.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
class ApiService {
|
||||
final String baseUrl;
|
||||
|
||||
ApiService({required this.baseUrl});
|
||||
|
||||
Future<dynamic> get(String endpoint, {Map<String, String>? headers}) async {
|
||||
final response = await http.get(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: headers,
|
||||
);
|
||||
return _processResponse(response);
|
||||
}
|
||||
|
||||
Future<dynamic> post(
|
||||
String endpoint,
|
||||
dynamic data, {
|
||||
Map<String, String>? headers,
|
||||
}) async {
|
||||
final response = await http.post(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: _jsonHeaders(headers),
|
||||
body: jsonEncode(data),
|
||||
);
|
||||
return _processResponse(response);
|
||||
}
|
||||
|
||||
Future<dynamic> postForm(String endpoint, Map<String, String> data) async {
|
||||
final response = await http.post(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
'accept': 'application/json',
|
||||
},
|
||||
body: data, // http package handles form-encoding for Map<String, String>
|
||||
);
|
||||
return _processResponse(response);
|
||||
}
|
||||
|
||||
Future<dynamic> put(
|
||||
String endpoint,
|
||||
dynamic data, {
|
||||
Map<String, String>? headers,
|
||||
}) async {
|
||||
final response = await http.put(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: _jsonHeaders(headers),
|
||||
body: jsonEncode(data),
|
||||
);
|
||||
return _processResponse(response);
|
||||
}
|
||||
|
||||
Future<dynamic> delete(
|
||||
String endpoint, {
|
||||
Map<String, String>? headers,
|
||||
}) async {
|
||||
final response = await http.delete(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: headers,
|
||||
);
|
||||
return _processResponse(response);
|
||||
}
|
||||
|
||||
Map<String, String> _jsonHeaders(Map<String, String>? extra) {
|
||||
return {'Content-Type': 'application/json', if (extra != null) ...extra};
|
||||
}
|
||||
|
||||
dynamic _processResponse(http.Response res) {
|
||||
final body = res.body.isNotEmpty ? jsonDecode(res.body) : null;
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
return body;
|
||||
} else {
|
||||
throw Exception('API error ${res.statusCode}: $body');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user