Making HTTP requests from a Flutter mobile app

Most mobile applications need to make requests to an external service, whether it’s an API, or any other service that’s hosted on an external server and can be accessed by making a request over HTTP. So, how do you make an HTTP call from a Flutter mobile app?

As discussed in a previous blog post, there are a lot of advantages to using an API. In this post, I will outline the steps needed to make a call to an external API, using HTTP, from a Flutter mobile app. The same concepts apply to the different types of Flutter apps as well.

There’s a package for that

To start off, you will need to include the http package in your application. Just add it to your pubspec.yaml file, and run the flutter pub get command. For more details on this package, check out its page on pub.dev.

After including the package in your app, you can start using it and making HTTP requests. To use it in your code, you have to add an import statement like this: import 'package:http/http.dart' as http.

GET requests

The easiest type of HTTP request to make, is a GET request. Here’s an example of how to make a GET request to an external server from your Flutter application: http.Response response = await http.get('https://example.com/api');

The above example uses the await keyword, which means that this line of code has to be inside a function that’s declared with the async keyword. This will make the call, and store the response in an object called response.

You can then read the response by using the below code: final Map<String, dynamic> responseData = json.decode(response.body);

This assumes that the external service that we’re calling returns data in JSON format. Otherwise, you will have to declare the variable responseData with the appropriate data type returned. To use the json.decode method, you have to import the built-in convert package like this (import 'dart:convert').

We are reading the contents of the response, by calling the body property. The Response object has another useful property called statusCode. This property contains the HTTP status code that was returned as a result of making the HTTP call. You can get a list of valid HTTP status code from here.

If we want to make sure that the call was successful, we can check the value of the statusCode property like this: if (response.statusCode == 200).

Here’s a complete example of making an HTTP GET request:

Future<void> getFamily() async {
    http.Response response = await http.get('https://example.com/api');
    final Map<String, dynamic> responseData = json.decode(response.body);
    if (response.statusCode == 200 || response.statusCode == 201) {
        // SUCCESS!
    } else {
        // THE CALL FAILED!
    }
    return;
}

Headers

If you need to set any headers before making the request, you can do so by passing a second argument to the http.get method. For example, if you want to set the Content-Type header value, the call would look like this:

http.Response response = await http.get('https://example.com/api', headers: {'Content-Type': 'application/json'});

POST requests

Making HTTP POST requests is very similar. Of course, with POST requests, the request can have data in its body. So, to make a POST request and pass data in the body, you have to use the http.post method. Typically, this method is called by passing 3 arguments. The first argument is the URL of the server you’re calling. The other two arguments are named. The first named argument is headers, which is used to set header values (just like in the get method). And the second named parameter is body, which is used to send data in the body of the request.

If you plan on sending data in JSON format, then you have to use the json.encode method.

Conclusion

In summary, to make HTTP calls from your Flutter mobile app, include the http package in your app and call the appropriate methods depending on the type of service you want to call. For any questions, please leave a comment here or use my contact page.

What is an API, and how it can save you money

You may have heard the term API before. For example, you may hear it if you try to integrate an existing service into your website. An invoicing website may use the API of a payment service provider to facilitate user payments in the website. Or, a mobile app may use a text-to-speech API to include this feature for the users of the app. But what is an API exactly, and how can you save money by using an API?

Defining an API

API stands for Application Programming Interface. It is a way for a developer, or a company, to expose their data or service for others to use. Others, means other developers, companies or simply other applications. And by exposing, I mean giving access to the functionality without revealing the source code or all the data in the database. Using an API has a lot of advantages when exposing a functionality to others. Not the least of which is controlling who has access to what. Users often access an API by providing an access code (or token). Based on this access code, the user can be identified, and their access is determined.

How an API saves you money

So, now that we know what an API is, the question is how does it save you money? Well, let’s say for example, you are a developer and you want to create a chat app. And, you want to keep the app family-friendly so everyone could use it. In this case, you have to make sure that all the messages exchanged through the app do not contain any curse words. Because the app is very popular, and millions of users are on it, it is not possible to manually moderate all the messages. The logical solution would be to automatically inspect every message, and flag it, if it’s inappropriate.

Even if technically you could develop this feature on your own, it would take you considerable effort to create something useable and fool-proof. And, even if you do decide to spend the time and effort to build this yourself, there’s the added work of having to maintain it. Unfortunately, curse words tend to evolve and change with time, so the database needs to be maintained and monitored all the time.

If you need it, someone has done it before

Instead of doing all this work yourself, you could use an existing API that provides this feature for you. As the saying goes, if you need it, someone has done it before. If you could use an existing API that provides a feature you’re looking for, this can potentially save you a lot of time and money as a developer. A great resource to search for available APIs, is a website called ProgrammableWeb. It has a huge searchable database of available APIs along with information about them.

Saving money as a client

Using an API can save you money not only as a developer, but as a client as well. For example, if you want to create a social networking website, and you hire a developer to create the website for you. To create a website like this, the developer will have to work on these key areas:

  • Database: where all the website data will be stored.
  • Backend code: this is usually the code that performs the business logic, and accesses the database.
  • Front-end code: this is the user interface that the user sees and interacts with. For example, the buttons and forms on the website.

Out of these three areas of the website, the backend code can be implemented as an API. And this is where you will potentially save money. Let’s say, after some time, the website becomes very popular and you decide you want to create a mobile application to go with the website. Well, if the backend was created as an API, then the only thing that the developers have to do is to create the mobile app’s front-end code. This is because the database is the same whether the data is being accessed by a website or a mobile app. And the backend is already an API, which can be used by a website or a mobile app.

Conclusion

Using APIs saves time and effort for developers, and ultimately, this means saving money for clients as well. So, for your next project, ask the developer if they’re going to use an API or not. And, if not, let them know the benefits of using an API. Here at W3 Applications, we always use APIs when creating web or mobile applications. This not only saves us time and effort, but saves money for our clients as well. If you have any questions about this, leave a comment here, or use the contact form. Thanks.