Search code examples
fluttergetrequest

Flutter: How to add headers to http package in flutter


I am trying to call the below API using the flutter package http, The structure of the request is

GET /api/v3/4870020/products/123123?lang=en&token=123456789abcd HTTP/1.1
Host: app.ecwid.com
Content-Type: application/json;charset=utf-8
Cache-Control: no-cache

How can I call this API using http package.


Solution

  • You can use get() from http package. Try this:

      Future<void> fetchData(String lang, String token) async {
        final host = "app.ecwid.com"; // this is your baseUrl
        final apiPath = "api/v3/4870020/products/123123"; // which api do you want to use?
        final url = "https://$host/$apiPath?lang=$lang&token=$token"; // final url
        final response = await http.get(
          url,
          headers: {
            "Content-Type": "application/json",
            "Cache-Control": "no-cache"
          }
        );
    
        if(response.statusCode == 200) {
          // do some stuff with the received data.
        }
        else return;
      }
    

    As you can see, we are specifying the language and token parameters to the end of the url.

    See the documentation