CodeBlanks Logo Icon CodeBlanks

API call

Send a request to the weather API with http.get.

Request with http.get

To fetch weather data from an API you use the get function from the http package. It returns a Future<Response>; you await it and reach the JSON string via response.body.

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

Future<String> havaGetir() async {
  final uri = Uri.parse('https://api.example.com/hava/istanbul');
  final response = await http.get(uri);
  return response.body;
}

URL with Uri.parse

http.get expects a Uri; you turn a plain string into a Uri with Uri.parse. Properly formatting the URL makes requests succeed.

final uri = Uri.parse('https://api.example.com/hava/ankara');
final response = await http.get(uri);
print(response.statusCode);  // 200

Practice The havaDurumuGetir function

Write an async function named havaDurumuGetir. Convert the URL to a Uri with Uri.parse, send a request with http.get, and return response.body. In main, parse the URL with Uri.parse and print it.

Starter code

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

// havaDurumuGetir fonksiyonunu yaz
// Uri.parse ile URL'yi çevir
// http.get ile isteği at ve response.body'yi döndür

void main() {
  // URL'yi Uri.parse ile çöz ve yazdır
}

Sample solution

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

Future<String> havaDurumuGetir() async {
  final uri = Uri.parse('https://api.example.com/hava/istanbul');
  final response = await http.get(uri);
  return response.body;
}

void main() {
  final uri = Uri.parse('https://api.example.com/hava/istanbul');
  print(uri);
}

Expected output

https://api.example.com/hava/istanbul

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the http.get call return?

  • Future<Response> Correct answer
  • Widget
  • void
  • String

Explanation: http.get returns a Future<Response>; after await you get the Response object. void has no return value, String is not direct (accessed via response.body), and Widget is for UI.

2 The http.get call

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

Future<String> getir() async {
  final uri = Uri.parse('https://api.example.com/hava/izmir');
  final response = await ____;
  return response.body;
}
Answer
import 'package:http/http.dart' as http;

Future<String> getir() async {
  final uri = Uri.parse('https://api.example.com/hava/izmir');
  final response = await http.get(uri);
  return response.body;
}

Explanation: http.get takes a Uri and sends a request; await waits for the Response. post is a different request, an empty call is incomplete, and jsonDecode does not take a URI.

3 http package parts

Term Meaning
http.get Sends a request to the API
Uri.parse Converts a string to a Uri
response.body Response body
await Waits for a Future

All lessons in Intermediate