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 iOS With React Native

TwitterFacebookRedditLinkedInHacker News

If you’ve been keeping up with my blog, you’ll know I did an article for doing HTTP requests with Ionic Framework. Since I’ve been playing around with React Native a lot lately, I figured it is probably a good idea to figure out how to do RESTful HTTP requests sooner than later since everything has an API back-end now.

The Facebook documentation for React Native has (or had at the time of writing this) a tutorial for getting movie data from a remote API. However, it hardly explained how to customize the HTTP request. In fact, I found that a lot of the internet was missing clear cut documentation for RESTful requests with React.

This article should clear things up!

Going forward I’m going to assume that you have a web application set up that you can use as your API endpoints. It doesn’t really matter how you’ve set it up as long as there is a GET endpoint and a POST endpoint. My endpoints are going to return the following data:

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.

Alright, now that the API stuff is out of the way, let’s see how to hit those endpoints with React Native.

We’re going to be making use of the fetch function. It can be better understood as follows:

fetch("API_ENDPOINT_HERE", {
    method: "",
    headers: {},
    body: ""
})
.then((response) => response.json())
.then((responseData) => {})
.done();

Note that the body option will not exist for GET requests.

So let’s try it out with our API endpoints:

fetch("http://www.example.com/test", {method: "POST", body: JSON.stringify({username: "nraboy", firstname: "Nic", lastname: "Raboy"})})
.then((response) => response.json())
.then((responseData) => {
    AlertIOS.alert(
        "POST Response",
        "Response Body -> " + JSON.stringify(responseData.body)
    )
})
.done();

The above code will hit our POST endpoint. It will pass a username, firstname, and lastname in the request body. When a response is received it will show an alert that spits out the returned content which is just the three properties recycled back to us.

This leaves us with the GET endpoint which can be seen below:

fetch("http://www.example.com/test?search=nraboy", {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
    AlertIOS.alert(
        "GET Response",
        "Search Query -> " + responseData.search
    )
})
.done();

In the above code there is a search query parameter. The endpoint will just spit that value back to us and we’ll display it as an alert. Nothing fancy in this example.

If you want to see this project in action, do the following, assuming you have React Native installed and are using a Mac. Using your Terminal, execute:

react-native init ReactProject

In your newly created project, open the index.ios.js file and replace all code with the following:

'use strict';

var React = require('react-native');

var {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    AlertIOS,
} = React;

var ReactProject = React.createClass({

    _onPressButtonGET: function() {
        fetch("http://localhost:3000/test?search=nraboy", {method: "GET"})
        .then((response) => response.json())
        .then((responseData) => {
            AlertIOS.alert(
                "GET Response",
                "Search Query -> " + responseData.search
            )
        })
        .done();
    },

    _onPressButtonPOST: function() {
        fetch("http://localhost:3000/test", {method: "POST", body: JSON.stringify({username: "nraboy", firstname: "Nic", lastname: "Raboy"})})
        .then((response) => response.json())
        .then((responseData) => {
            AlertIOS.alert(
                "POST Response",
                "Response Body -> " + JSON.stringify(responseData.body)
            )
        })
        .done();
    },

    render: function() {
        return (
            <View style={styles.container}>
                <TouchableHighlight onPress={this._onPressButtonGET} style={styles.button}>
                    <Text>GET</Text>
                </TouchableHighlight>
                <TouchableHighlight onPress={this._onPressButtonPOST} style={styles.button}>
                    <Text>POST</Text>
                </TouchableHighlight>
            </View>
        );
    },

});

var styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    button: {
        backgroundColor: '#eeeeee',
        padding: 10,
        marginRight: 5,
        marginLeft: 5,
    }
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);

React Native Fetch

Not too bad right?

Conclusion

Even though it is not easily understandable through the minimal amount of documentation that appears online, making fetch calls at RESTful HTTP endpoints is not difficult in React Native.

A video version of this article can be seen below.

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.