Flutter — all you need to know about the http package

photo from https://www.pexels.com/photo/abstract-art-blur-bright-373543/

Foreword…

When we are developing mobile phone apps, it is not uncommon to make API calls through the http protocol. For some cases, the target API provider would provide a library for some specific programming languages which would ease the development at once. However for most situations, the API provider only exposes the REST API layer and let developers build its own http connectivity code.

The Sample app

We build on top of a sample app to illustrate what challenges would be encountered and, of course, how to solve them piece by piece.

1st tab — suggestion from the bored-activity API :)

feel bored? Get a suggestion from the API :))

2nd tab — making a Query to Elasticsearch Cloud Service

search against Elasticsearch Cloud Service
  • provides a url to access (value denoted in the config file)

3rd tab — add a document to Elasticsearch Cloud Service

If you make it through this point; probably running a POST request is a piece of cake to you :) Indeed, we could simply use the built-in POST method— told you it is easy.

add a new document based on a Jog or Read event.

How to run the code??

Q. first… where and how to get the code

Q. hey… when I try to build the Flutter project, it states that a resource file config.json is missing?

  • yes, you would need to add back a config file under the assets folder
  • es_user => the account for authentication (probably is “elastic”)
  • es_pwd => the password for the es_user .
  • es_index => set to any index name you prefer (default is “blog_activity”)

Q. hm… I don’t have a Elasticsearch Cloud Service, but want to setup one

Q. what if… I do host a Elasticsearch cluster on my own premises PLUS I didn’t setup any authentications ~~~

  • scenario 1 -> if you host Elasticsearch on your own; simply update the config.json to the corresponding url plus the username / password pair; that should do the trick.
  • scenario 2 -> you didn’t have authentications setup for the cluster. Then you could just setup the es_url value and ignore the es_user and es_pwd. The corresponding code change would be commenting the authentication header (e.g. key: Authorization), also you would comment out the code from reading the es_user and es_pwd values (e.g. configLoader.getConfigByKey(…) ).

Closings

As usual we did a great job on exploring a journey. This time we have accomplished a few things as follows:

  • making requests by using the http built-in methods
  • created a custom Client to handle customisable request(s) — “get”
  • understood how to set http headers to the request
  • understood how BASIC authentication could be set for connecting a secured service (Elasticsearch Cloud Service in this example)

a java / golang / flutter developer, a big data scientist, a father :)