Dealing with REST API’s in Flutter

Hey everyone, Welcome to our new blog post. In this post, we will discuss on making REST API calls from your Flutter Application. Before we delve into implementation, let’s know what is REST API and then how to use them in Flutter.

REST API

REST refers to Representational State Transfer. It adheres to the practice of transferring object based data via internet. So whenever, client requests data from server, Server creates an object of that type and sends it to client and vice versa is also the same.

How to make a call ?

We make API calls using Hyper Text Transfer Protocol or HTTP. To give a brief understanding of protocol, it can be understood as a set of rules to transfer data typically files, images etc. Almost every address you browse in modern browser, uses either HTTP or HTTPs. The difference between HTTP and HTTPs is that, the former transfer data in the form of plain text while the later transfers data as a cipher text. Example: https://learnai1.home.blog/

Types of HTTP calls

  • GET : Used to get data from server.
  • PUT : Used to edit data from sever.
  • POST : Used to post data to server.
  • DELETE : Used to delete data in server.

Making API calls in Flutter

Flutter is an open source development framework, which enables us to have several plugins which serve the same purpose. To make http calls, we have several plugins like http, dio etc.

We will use http plugin in this blog post. To add that plugin into our application only pubspec.yaml file in the root of your flutter project and add http to your dependencies as shown below.

Dependency in pubspec.yaml

For tutorial purposes, we will develop an application in which we will display a random programming joke every time you open the application. Sounds great right let’s do it. We will make use of this url to get random jokes.

A look on sample data

πŸ˜‚πŸ˜‚

Now that we have data ready, we need to know how to make a GET request in flutter application.

This is how our application looks at the end. Now Let’s code it.

screenshot

Let’s code now..!

Create a new Flutter project with the name random_programming_joke. Use the following command to do so, then open the folder in your editor.

flutter create random_programming_joke

As we have already talked about REST architecture, it maps object to data. So we need to create a class which looks like the incoming json. Create a file in lib folder called model.dart and add the following code.

import 'dart:convert';

List<RandomJoke> randomJokeFromJson(String str) => List<RandomJoke>.from(json.decode(str).map((x) => RandomJoke.fromJson(x)));

String randomJokeToJson(List<RandomJoke> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class RandomJoke {
    RandomJoke({
        this.id,
        this.type,
        this.setup,
        this.punchline,
    });

    int id;
    String type;
    String setup;
    String punchline;

    factory RandomJoke.fromJson(Map<String, dynamic> json) => RandomJoke(
        id: json["id"],
        type: json["type"],
        setup: json["setup"],
        punchline: json["punchline"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "type": type,
        "setup": setup,
        "punchline": punchline,
    };
}

In the above piece of code, we created a dart class with the attributes as in sample json data. randomJokeToJson and randomJokeFromJson are the utility functions which map the json to object and object to json to communicate with server.

Now that we have the code to deal with data, all we need to do is to make a REST API call and GET the data from server, so let’s create a new .dart file in our project to get data and name it as getdata.dart .

Add the following lines of code to that file.

import 'model.dart';
import 'package:http/http.dart' as http;
Future<RandomJoke> getData() async{
  var response=await http.get("https://official-joke-api.appspot.com/jokes/programming/random");
  if(response.statusCode==200){
    return randomJokeFromJson(response.body)[0];
  }
  else{
    throw Exception;
  }
}

We will import our http plugin and use get method to get the data from url. response is returned by HTTP GET request, which has a status code which when equal to 200, means a success.

Now we will add the following code to the main.dart file in our Flutter project, to render them on our application.

import 'package:random_programming_joke/get_data.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Random Programming Joke",
      theme: ThemeData.dark(),
      home: Scaffold(appBar: AppBar(title: Text("Random Programming Joke"),
      backgroundColor: Colors.lightBlueAccent,
      ),
      body: FutureBuilder(
        future: getData(),
        builder: (context, snapshot){
        if(snapshot.hasData){
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
            Card(child: Container(child: Text(snapshot.data.setup,textAlign: TextAlign.center,),
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.all(50),
            ),
            elevation: 5,
            shadowColor: Colors.yellow,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15),),
            color:Colors.red,
            ),
            Card(child: Container(child: Text(snapshot.data.punchline,textAlign: TextAlign.center,),
            width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.all(50),
            ),
            elevation: 5,
            shadowColor: Colors.blue,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15),),
            color: Colors.green,
            )
          ],);
        }
        else{
          return Center(child:CircularProgressIndicator());
        }
      },),
      ),
    );
  }
}

You can download the whole project from my github repo. Now, run the application and laugh every time you open the applicationπŸ˜‚πŸ˜‚.

Thanks for reading. Keep Learning. Have a great day. Cheers..✌✌

Leave a comment

Design a site like this with WordPress.com
Get started