Rest API in Flutter

If you have worked on mobile app development, you probably would have heard about API.

API in a mobile app is required to allow users to communicate with other applications. This can be a backend server developed by you or even by any other company like Facebook, Google etc.

REST API follows REST protocol and uses HTTP requests to communicate. Requests can be of GET, POST, PUT, DELETE type. These requests are used to handle data. REST API can also be understood as an architecture type used for creating web-services for your mobile app.

For flutter apps, developers can integrate them into the backend, along with UI development. We can use REST API for this because it uses simple HTTP requests and JSON for communication.

Features like asynchronous (using async and await keywords) programming makes it even better to use.

To make the process even easier for developers, the flutter team has provided the HTTP package.

STEP 1: Basic setup in the project

To add the HTTP package to your project, we must make some changes to the pubspec.yaml file.

This file is already a part of your project package when a new project is created.

dependencies:

  http: ^0.12.2

You can install the package:

  • Using Pub:
$ pub get
  • Using Flutter:
$ flutter pub get

Now to use it in your dart code, you can import using : 

import 'package:http/http.dart';

STEP 2: Create a request 

The basic request below uses the GET HTTP method to fetch the data from the given URL in JSON format. Each request returns a Response class object. 

A Future<> is used to represent a potential value or error that will be available at some time in the future. Since you have made a request to a server now, but the response will actually be available later in future. In our code, we haven’t used Future<Response>. 

Here, we use the async & await feature which ensures that the response is asynchronous which means until & unless we get the response, code will not move further.

This will ensure that method will not return until the response is actually received.

String url = "Your_URL";

Response getRequest() async {

final response = await http.get(url);

return response;

}


(Another example)


import 'package:http/http.dart' as http;

String url = 'https://………./resource’;

Response response = await http.post(url, 

                                                                  body: {'name': ‘Name’, 'color': ‘black’});

print('Response status: ${response.statusCode}');

print('Response body: ${response.body}');

STEP 3: Create  a Response class

class Response { 

  final int id; 

  final String title;  

  Response( 

    this.id, 

    this.title,

  ); 

}

STEP 4: Displaying the JSON data after decoding it

ex : 

List<Fruit> decodetheResourceEntity(String responseBody) {

 final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

 return parsed.map<ResourceEntity>((json) => ResourceEntity.fromMap(json)).toList();

}

Other than fetching the data from the servers, we can also update, delete and send the data to the backend servers. The code for that is shown below.

Code for Updating the data :

Resource updateResource(String title, int id) async { 

final http.Response response = await http.put( 

‘http://url/…..’, 

headers: <String, String>{ 

'Content-Type': 'application/json; charset=UTF-8', 

}, 

body: jsonEncode(<String, String>{ 

'title': title, 

}), 

); 

if (response.statusCode == 200) { 

return Resource.fromJson(json.decode(response.body)); 

} else { 

throw Exception('Failed to update.'); 

} 

}

Code for deleting the data :

Resource deleteResource(int id) async { 

final http.Response response = await http.delete( 

‘http://url/…….', 

headers: <String, String>{ 

'Content-Type': 'application/json; charset=UTF-8', 

}, 

); 

if (response.statusCode == 200) { 

return Resource.fromJson(json.decode(response.body)); 

} else { 

throw Exception('Failed to delete.'); 

} 

}

Code for Sending data using the POST request:

Resource saveResource( 

String title, int id) async { 

final http.Response response = await http.post( 

‘http://url/…….',  

headers: <String, String> { 

'Content-Type': 'application/json; charset=UTF-8', 

}, 

body: jsonEncode(<String, String> { 

'title': title, 

'id': id,

}), 

); 

if (response.statusCode == 200) { 

return Resource.fromJson(json.decode(response.body)); 

} else { 

throw Exception('Failed to save the resource); 

} 

}

 

Leave a Reply