POST GET PUT DELETE

Fuel your HTTP Requests for Kotlin

While we all were busy retrofit-ing our HTTP requests on Android, I stumbled across this amazing and easy to use HTTP library called Fuel!

Let me show you how easy your HTTP requests on Android can be ☺️

The Setup:

I will be covering Fuel + Gson, hence here are the required dependencies for the build.gradle file:

repositories {
    jcenter()
}

dependencies {
    compile 'com.github.kittinunf.fuel:fuel:1.12.0' //for JVM
    compile 'com.github.kittinunf.fuel:fuel-android:1.12.0' //for Android
    compile 'com.github.kittinunf.fuel:fuel-gson:1.12.0' //for Gson support
    compile 'com.google.code.gson:gson:2.8.2' //Gson
}

That’s it!

A Simple Get Request with Fuel:

Let’s GET this URL: dummy.restapiexample.com/api/v1/employee/1

"dummy.restapiexample.com/api/v1/employee/1".httpGet().responseString 
{ request, response, result ->
               print("APIResponse", result.toString())
}

Which should print out:

{   
    "id":"1",
    "employee_name":"",
    "employee_salary":"0",
    "employee_age":"0",
    "profile_image":""
}

That’s all for GET, now let’s try a POST request.

POST request with Fuel:

Let’s POST this URL: http://httpbin.org/post

    Fuel.post("http://httpbin.org/post").body("{ \"foo\" : \"bar\" }").response { request, response, result ->
        //Which results in a success
    }

Ok, that’s great and all. You and I both write clean code and we pretty much use Model objects that are Serialised for our HTTP POST requests.

Well, if you are like me and if you use Gson for Serialising-Deserialising your Model objects, then let me show you how easy that is as well!

POST request with Gson and Fuel:

A typical Kotlin Model class would look like:

data class Person( val firstName:String,
                   val lastName:String,
                   val address:String,
                   val planet:String) { }

Let’s create an Instance of the Person Object:

 val person = Person( firstName: "Basanth",
                      lastName: "Verma", 
                      address: "127.0.0.1",
                      planet: "Mars")

 //Serialising it to Json using Gson
 val personJson = Gson().toJson(person)

Let’s make that POST request!

 "yourServerBaseURL.com/createPerson".httpPost().header("Content-Type" to "application/json").body(personJson.toString()).response { req, res, result ->
    //Ought to be a Success!                
 }

It’s important to set the “Content-Type” to “application/json” after serialising with Gson, otherwise your server may receive the personJson within another json object.

This saves a whole lot of burden with the setup that other HTTP libraries require. However you may be interested in the Router-pattern and such for your services, which I believe can be setup using Fuel as well.

That’s all for today! I hope this quick blog of mine was helpful to you. Feel free to comment your questions!

Source: https://github.com/kittinunf/Fuel