What is API?

·

2 min read

API means application programming interface.

API is a way to connect to a database/webserver with the client.

API Example - 1

Let's say that you went to a KFC shop and the waiter will give you a menu to order items. You as the customer will choose the items and tell the waiter what you want to have. Post that waiter will go to the kitchen and tell the cook to prepare the order and bring items to the table once the food is ready.

In the above example, the waiter is API Service where he connects with Web-Server and Database to get the items and show them in the UI.

In Flutter we use the package called HTTP to enable the usage of API.

http | Dart Package (pub.dev) - In this link, we find the latest information about the HTTP package.

Once the package is added, we need to test the endpoint in Postman.

Install the plugin in Android Studio:

The above plugin helps us to write model classes very easily.

The HTTP package is a Future-based library for making HTTP requests.

What is Future-Based? - if a function returns its value with a delay of some time.

Example:

Future<List<Photos>> getPhotos() async {
  var response = await http
      .get(Uri.parse("https://jsonplaceholder.typicode.com/photos")); //End Point url
  var data = jsonDecode(response.body.toString()); //decode the data from response

  if (response.statusCode == 200) {
   //do Something
    }

  } else {
       //do Something
  }
}
Note: Status Code 200 means, success.

Additionally, you can explore using the fake API which is available on the site :
JSONPlaceholder - Free Fake REST API (typicode.com)

Let me know if the above information helped you kick-start your journey to use the API in Flutter.

Please share your feedback.

Rahul