A RESTful API Client is a software component or application that interacts with a web service or API following the principles of REST. It’s designed to send HTTP requests, such as GET
, POST
, PATCH
, and DELETE
to specific endpoints of a web service, retrieving, updating, creating, or deleting resources. A RESTful API Client abstracts the complexities of HTTP communication, providing a structured way to consume and interact with RESTful APIs programmatically. In this Answer, we will learn to create a RESTful API Client in Dart.
Let's go through each step that will enable us to create a RESTful API Client in Dart.
pubspec.yaml
fileEverything has been set up for you on our platform. However, if you are working on your local system or machine, make sure the pubspec.yaml
file within the Dart project is set up as follows:
name: restful_api_clientdescription: A RESTful API Client in Dartversion: 1.0.0environment:sdk: ^3.2.3dependencies:http: ^1.1.2
Once the pubspec.yaml
file has been set up, we need to import the required packages within the relevant Dart file. The code snippet below shows how to import the relevant packages within the Dart file.
import 'package:http/http.dart' as http;import 'dart:convert';
In the code snippet above, we import the http
and dart:convert
packages. The http
package in Dart facilitates HTTP requests (GET
, POST
, PATCH
, and DELETE
) to interact with RESTful APIs. It enables communication with web services, sending requests to specific endpoints, and handling responses, allowing the creation of RESTful API Clients programmatically. On the other hand, the dart:convert
package allows us to handle JSON encoding and decoding.
http
packageOnce the above-mentioned steps have been completed, we can start making HTTP requests in Dart using the http
package to create the RESTful API Client. We’ll be making the following requests:
GET
: Retrieve data from the server.
POST
: Create new resources on the server.
PATCH
: Update existing resources partially on the server.
DELETE
: Remove resources from the server.
Note: We'll be using the API and end-points provided by
to make the above-mentioned requests. Fake Store API https://fakestoreapi.com/
GET
requestThe coding playground below shows how to make a GET
request in Dart using the http
package. Execute the code below by pressing the "Run" button and see the output within the terminal.
import 'package:http/http.dart' as http; import 'dart:convert'; Future<void> get_request() async { try { print(''); print('Making GET request...'); var response = await http.get(Uri.parse('https://fakestoreapi.com/products/1')); if (response.statusCode == 200) { Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('GET request successful!'); } else { print('Failed to fetch data: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> main() async { await get_request(); }
In the code snippet above:
Line 4: We define an asynchronous function named get_request()
that will be used to make a GET
request.
Line 8: We send a GET
request to the specified URL.
Lines 9–14: If the request is successful, we decode the JSON response body and print each key-value pair present within the response body. We then print the relevant success message.
Lines 15–17: If the request is not successful, we print the relevant failure message.
Lines 18–20: We catch any exception and print the exception message.
Lines 23–25: We define an asynchronous main()
function and call the get_request()
function.
POST
requestThe coding playground below shows how to make a POST
request in Dart using the http
package. Execute the code below by pressing the "Run" button and see the output within the terminal.
import 'package:http/http.dart' as http; import 'dart:convert'; Future<void> post_request() async { try { print(''); print('Making POST request...'); Map<String, dynamic> requestBody = { 'title': 'test product', 'price': 13.5, 'description': 'lorem ipsum set', 'image': 'https://i.pravatar.cc', 'category': 'electronic' }; var response = await http.post( Uri.parse('https://fakestoreapi.com/products'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(requestBody), ); if (response.statusCode == 200) { print("Product with the following details created successfully:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('POST request successful!'); } else { print('Failed to make POST request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> main() async { await post_request(); }
In the code snippet above:
Line 4: We define an asynchronous function named post_request()
that will be used to make a POST
request.
Lines 8–14: We create a Map
object called requestBody
that contains the key-value pairs representing the details of the product to be created.
Lines 15–21: We send a POST
request to the specified URL with specified headers and the JSON-encoded requestBody
.
Lines 22–28: If the request is successful, we decode the JSON response body and print each key-value pair present within the response body. We then print the relevant success message.
Lines 29–31: If the request is not successful, we print the relevant failure message.
Lines 32–34: We catch any exception and print the exception message.
Lines 37–39: We define an asynchronous main()
function and call the post_request()
function.
PATCH
requestThe coding playground below shows how to make a PATCH
request in Dart using the http
package. Execute the code below by pressing the "Run" button and see the output within the terminal.
import 'package:http/http.dart' as http; import 'dart:convert'; Future<void> patch_request() async { try { print(''); print('Making PATCH request...'); Map<String, dynamic> requestBody = { 'title': 'test product', 'price': 13.5, 'description': 'lorem ipsum set', 'image': 'https://i.pravatar.cc', 'category': 'electronic' }; var response = await http.patch( Uri.parse('https://fakestoreapi.com/products/7'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(requestBody), ); if (response.statusCode == 200) { print("Product patched successfully. Here are the details of the updated product:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('PATCH request successful!'); } else { print('Failed to make PATCH request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> main() async { await patch_request(); }
In the code snippet above:
Line 4: We define an asynchronous function named patch_request()
that will be used to make a PATCH
request.
Lines 8–14: We create a Map
object called requestBody
that contains the key-value pairs representing the details of the product to be created.
Lines 15–21: We send a PATCH
request to the specified URL with specified headers and the JSON-encoded requestBody
.
Lines 22–28: If the request is successful, we decode the JSON response body and print each key-value pair present within the response body. We then print the relevant success message.
Lines 29–31: If the request is not successful, we print the relevant failure message.
Lines 32–34: We catch any exception and print the exception message.
Lines 37–39: We define an asynchronous main()
function and call the patch_request()
function.
DELETE
requestThe coding playground below shows how to make a DELETE
request in Dart using the http
package. Execute the code below by pressing the "Run" button and see the output within the terminal.
import 'package:http/http.dart' as http; import 'dart:convert'; Future<void> delete_request() async { try { print(''); print('Making DELETE request...'); var response = await http.delete( Uri.parse('https://fakestoreapi.com/products/6'), ); if (response.statusCode == 200) { print("Product deleted successfully. Here are the details of the deleted product:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('DELETE request successful!'); } else { print('Failed to make DELETE request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> main() async { await delete_request(); }
In the code snippet above:
Line 4: We define an asynchronous function named delete_request()
that will be used to make a DELETE
request.
Lines 8–10: We send a DELETE
request to the specified URL.
Lines 11–17: If the request is successful, we decode the JSON response body and print each key-value pair present within the response body. We then print the relevant success message.
Lines 18–20: If the request is not successful, we print the relevant failure message.
Lines 21–23: We catch any exception and print the exception message.
Lines 26–28: We define an asynchronous main()
function and call the delete_request()
function.
The coding playground below combines all the above requests and creates the RESTful API Client. Execute the code below by clicking the "Run" button and see the output within the terminal.
import 'package:http/http.dart' as http; import 'dart:convert'; class RESTful_API_Client { Future<void> get_request() async { try { print(''); print('Making GET request...'); var response = await http.get(Uri.parse('https://fakestoreapi.com/products/1')); if (response.statusCode == 200) { Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('GET request successful!'); } else { print('Failed to fetch data: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> post_request() async { try { print(''); print('Making POST request...'); Map<String, dynamic> requestBody = { 'title': 'test product', 'price': 13.5, 'description': 'lorem ipsum set', 'image': 'https://i.pravatar.cc', 'category': 'electronic' }; var response = await http.post( Uri.parse('https://fakestoreapi.com/products'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(requestBody), ); if (response.statusCode == 200) { print("Product with the following details created successfully:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('POST request successful!'); } else { print('Failed to make POST request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> patch_request() async { try { print(''); print('Making PATCH request...'); Map<String, dynamic> requestBody = { 'title': 'test product', 'price': 13.5, 'description': 'lorem ipsum set', 'image': 'https://i.pravatar.cc', 'category': 'electronic' }; var response = await http.patch( Uri.parse('https://fakestoreapi.com/products/7'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(requestBody), ); if (response.statusCode == 200) { print("Product patched successfully. Here are the details of the updated product:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('PATCH request successful!'); } else { print('Failed to make PATCH request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } Future<void> delete_request() async { try { print(''); print('Making DELETE request...'); var response = await http.delete( Uri.parse('https://fakestoreapi.com/products/6'), ); if (response.statusCode == 200) { print("Product deleted successfully. Here are the details of the deleted product:"); Map<String, dynamic> data = json.decode(response.body); data.forEach((key, value) { print('$key: $value'); }); print('DELETE request successful!'); } else { print('Failed to make DELETE request: ${response.statusCode}'); } } catch (e) { print('Exception occurred: $e'); } } } Future<void> main() async { RESTful_API_Client client = RESTful_API_Client(); await client.get_request(); await client.post_request(); await client.patch_request(); await client.delete_request(); }
In the code snippet above:
Lines 4-111: We define a class named RESTful_API_Client
and make the methods get_request()
, post_request()
, patch_request()
, and delete_request()
part of the RESTful_API_Client
class.
Lines 113–119: We define an asynchronous main()
function. In this function, we create an object named client
of the RESTful_API_Client
class. Finally, we call the methods of the RESTful_API_Client
class.
We have learned how to create a RESTful API Client in Dart. We also learned to make various HTTP requests—GET
, POST
, PATCH
, and DELETE
. Through the http
package and JSON encoding/decoding in Dart, we have learned to communicate with API endpoints, retrieve data, create new resources, update existing ones, and delete specific elements. Understanding these fundamental concepts empowers developers to effectively utilize Dart for building applications that seamlessly interact with web services, providing a foundation for comprehensive API integration in their projects.
Free Resources