Consume a REST API in Flutter.

Author
By Darío Rivera
Posted On in Flutter

To consume a REST API in Flutter we can use the http package. This package provides all the necessary methods to establish an HTTP communication with other servers. Below you will see some examples of how we can use this package to make different requests.

Get

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

Response response = await get('https://jsonplaceholder.typicode.com/todos/1');
Map data = jsonDecode(response.body);
print(data);
I/flutter (32115): {userId: 1, id: 1, title: delectus aut autem, completed: false}

Post

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

Response response = await post('https://jsonplaceholder.typicode.com/posts',
    body: {'title': 'Post Title', 'body': 'Lorem ipsum', 'userId': '1'}
);
Map data = jsonDecode(response.body);
print(data);
I/flutter ( 9532): {title: Post Title, body: Lorem ipsum, userId: 1, id: 101}

Query params

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

var url =
Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': 'http', 'callback': 'handle'});
Response response = await get(url);

print(response.body);
I/flutter ( 9532): // API callback
I/flutter ( 9532): handle({
I/flutter ( 9532):   "kind": "books#volumes",
I/flutter ( 9532):   "totalItems": 1012,
I/flutter ( 9532):   "items": [
I/flutter ( 9532):     {
...

Acerca de Darío Rivera

Author

Application Architect at Elentra Corp . Quality developer and passionate learner with 10+ years of experience in web technologies. Creator of EasyHttp , an standard way to consume HTTP Clients.

LinkedIn Twitter Instagram

Sólo aquellos que han alcanzado el éxito saben que siempre estuvo a un paso del momento en que pensaron renunciar.