From 0dcdaaf6413b123818c2e2b46eabc511878dece9 Mon Sep 17 00:00:00 2001 From: hunteraraujo Date: Thu, 31 Aug 2023 14:46:01 -0700 Subject: [PATCH] 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. --- lib/utils/rest_api_utility.dart | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 lib/utils/rest_api_utility.dart diff --git a/lib/utils/rest_api_utility.dart b/lib/utils/rest_api_utility.dart new file mode 100644 index 00000000..47e355a0 --- /dev/null +++ b/lib/utils/rest_api_utility.dart @@ -0,0 +1,40 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +class RestApiUtility { + final String baseUrl; + + RestApiUtility(this.baseUrl); + + Future> 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> 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> post( + String endpoint, Map 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'); + } + } +}