Connect to 3rd Party APIs Easily with Flutter App
Connecting to 3rd Party APIs From Flutter App
Flutter is quickly becoming the go-to framework for creating amazing mobile apps for both iOS and Android operating systems. With its powerful cross-platform capabilities, it’s no wonder developers are beginning to use Flutter for more than just building user interfaces. One of those features is connecting to third-party APIs to fetch data and build powerful features such as analytics, push notifications, and more.
In this post, we will look at how to connect to a third-party API from a Flutter app using the http package. We will use the open weather API as our 3rd party API to give our users local weather information.
Getting Started
The first step in getting started with connecting to an API from your Flutter app is to add the http dependency to your pubspec.yaml file. This will allow us to make API calls and get the data back from the server.
Once the dependency is added, we can then move on to writing the code that will make the API call and get the data. In this example, we will be using the open weather API and will be passing in the city name as a parameter to get the current weather information for that location.
We will start by creating a function that will make the API call. This function will take the city name as a parameter and return the weather information for that city. The code below shows the basic structure of the function:
Future getWeatherByCityName(String cityName) async {
// Make the API call to get the weather information
// Parse the response and return the Weather object
}
The next step is to make the actual API call. We will do this using the http package. The code below shows how to make the API call and parse the response into a Weather object.
final response = await http.get('https://api.openweathermap.org/data/2.5/weather?q=$cityName&APPID=${your_api_key_here}');
if (response.statusCode == 200) {
// Parse the response into a Weather object
final Weather weather = Weather.fromJson(json.decode(response.body));
return weather;
} else {
throw Exception('Failed to load weather data');
}
Once the response is parsed, we can then access the data inside the Weather object. For example, in our case, we can use the following to get the temperature and humidity of the city:
weather.temperature;
weather.humidity;
And that’s it! With the code above, you can now connect to 3rd party APIs from your Flutter app and get the data you need for your application.