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.

You can install the package:

  • Using Pub:

  • Using Flutter:

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

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.

STEP 3: Create  a Response class

STEP 4: Displaying the JSON data after decoding it

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 :

Code for deleting the data :

Code for Sending data using the POST request:

 

Leave a Reply