Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Make HTTP Requests In A NativeScript Mobile Application

TwitterFacebookRedditLinkedInHacker News

As I mentioned in some of my other posts, I’ve been exploring NativeScript by Telerik. So far it has proven to be a nifty platform and my attention is still invested. Previously when writing about similar technologies such as React Native and Ionic Framework, I explained how to make HTTP requests to third party web services. I demonstrated how to make HTTP requests in Ionic Framework as well as how to make HTTP requests in React Native. This time I figured it was time to do the same demonstration with NativeScript.

In this guide we’ll take a look at how to make requests against a RESTful API server in an Android and iOS app using Telerik NativeScript.

Let’s go ahead and create a fresh NativeScript Android and iOS project by executing the following in our Command Prompt (Windows) or Terminal (Mac and Linux):

tns create ExampleProject
cd ExampleProject
tns platform add ios
tns platform add android

Keep in mind that if you’re not using a Mac computer, you cannot add and build for the iOS platform.

Like with React Native, we’re going to be using the JavaScript fetch function for communicating with a remote service. However, first we need to define such a service.

Because full stack application development is outside the scope of this particular tutorial, we’re going to use a bit of our imagination. Let’s assume we have the following API endpoint responses:

GET /test

{
    status: "success",
    message: "a sample GET request",
    search: {{QUERY.search}}
}

In the above response, QUERY.search is a parameter to be passed into the request. The response is just returning the query parameter passed.

POST /test

{
    status: "success",
    message: "a sample POST request",
    body: {
        username: {{BODY.username}}
        firstname: {{BODY.firstname}}
        lastname: {{BODY.lastname}}
    }
}

In the above response, BODY.username is a property in the JSON body that was passed in the request. Likewise with the BODY.firstname and BODY.lastname properties.

If you really wanted to make your own web API, you can check out the tutorial I wrote for building a CEAN stack application with Node.js.

Alright, with our theoretical API endpoints out of the way, let’s worry about making requests against them.

In our project, open the app/main-page.xml and change the XML to look like the following:

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="pageLoaded">
    <StackLayout>
        <Button text="GET" tap="getRequest" />
        <Button text="POST" tap="postRequest" />
    </StackLayout>
</Page>

For simplicity we only want two buttons. One button for the GET request and one button for the POST request.

Now let’s move onto the app/main-page.js file. As mentioned earlier, we’re going to use the fetch function, but first we need to include it into the JavaScript file:

var fetchModule = require("fetch");

With fetchModule in place we can carry out our requests with something similar to this:

fetchModule.fetch("API_ENDPOINT_HERE", {
    method: "",
    headers: {},
    body: ""
})
.then(function(response) {
    console.log(JSON.stringify(response));
}, function(error) {
    console.log(JSON.stringify(error));
});

Let’s see this example through. Inside your app/main-page.js file replace everything with the following:

var fetchModule = require("fetch");

function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = { };
}

exports.pageLoaded = pageLoaded;

exports.getRequest = function() {
    fetchModule.fetch("https://www.example.com/test?search=Hello", {
        method: "GET"
    })
    .then(function(response) {
        alert({title: "GET Response", message: JSON.stringify(response), okButtonText: "Close"});
    }, function(error) {
        console.log(JSON.stringify(error));
    })
}

exports.postRequest = function() {
    fetchModule.fetch("https://www.example.com/test", {
        method: "POST",
        body: JSON.stringify({username: "nraboy", firstname: "Nic", lastname: "Raboy"})
    })
    .then(function(response) {
        alert({title: "POST Response", message: JSON.stringify(response), okButtonText: "Close"});
    }, function(error) {
        console.log(JSON.stringify(error));
    })
}

The result should look something similar to the following:

Fetch with NativeScript

When you click the buttons, an alert will show with the response. Of course in the above screenshots the response doesn’t quite match what we listed earlier, but that is only because I’m using a different API.

Conclusion

Like with similar web hybrid mobile technologies, making HTTP requests with NativeScript was not much different nor difficult. We made use of the fetch function which is common in JavaScript for making asynchronous requests.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.