How to make RESTful API calls?

To make RESTful API calls, requests should be sent from an HTTP client in JavaScript or Python to the API endpoint.

How to make RESTful API calls?

Overview

In the world of web development, communicating with external services and fetching data from APIs is a common task. RESTful APIs have become the standard for building and consuming web services due to their simplicity and scalability.

In this guide, we will explore how to make RESTful API calls in popular programming languages such as Python, JavaScript, TypeScript, Go and C#. We'll provide code examples in each language to help you get started.

Python

Python is a versatile language known for its simplicity and readability. To make RESTful API calls in Python, you can use the requests library.

import requests

url = "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>"
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print('Currency Exchange API request failed.')

In this example, we use the requests.get() method to send a GET request to the Currency Exchange API endpoint.

If the response status code is 200 (OK), we parse the JSON response. You can also include headers and parameters in your requests if needed.

JavaScript (Node.js)

Node.js allows you to run JavaScript on the server-side. To make RESTful API calls in JavaScript, you can use the axios library, which is known for its simplicity and flexibility.

const axios = require('axios');

const url = "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

axios.get(url)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error('API request failed:', error);
  });

Here, we use axios.get() to send a GET request and handle the response and errors using Promises.

TypeScript

TypeScript is a statically typed superset of JavaScript, and it's becoming increasingly popular for building scalable applications. Making RESTful API calls in TypeScript is similar to JavaScript, with the added benefit of type checking.

import axios from 'axios';

const url = "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

axios.get(url)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error('API request failed:', error);
  });

The TypeScript code is almost identical to JavaScript, but it provides better type safety and code intelligence.

Go

Go, also known as Golang, is a statically typed language known for its efficiency and performance. To make RESTful API calls in Go, you can use the built-in net/http package.

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
    url := "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

	response, err := http.Get(url)
	if err != nil {
		fmt.Println("API request failed:", err)
		return
	}
	defer response.Body.Close()

	if response.StatusCode == 200 {
		body, _ := ioutil.ReadAll(response.Body)
		fmt.Println(string(body))
	} else {
		fmt.Println("API request failed. Status code:", response.StatusCode)
	}
}

In Go, we use the http.Get() function to send a GET request, and we read the response body and handle errors accordingly.

Bash

Bash is a powerful shell scripting language commonly used in Unix-like operating systems. While it's not typically associated with web development, you can still make RESTful API calls using tools like curl. Here's a simple example of making an API GET request in Bash:

#!/bin/bash

# Define the API endpoint
api_url="https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

# Make a GET request using curl
response=$(curl -s "$api_url")

# Print the response
echo "$response"

In this script:

  • We specify the API endpoint in the api_url variable.
  • We use curl -s to make a GET request to the API and store the response in the response variable.
  • Finally, we echo the response to the console.

PHP

PHP is a widely-used server-side scripting language known for its web development capabilities. You can use the curl library in PHP to interact with RESTful APIs. Here's an example:

<?php

// Define the Currency Exchange API endpoint
$api_url = "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request and store the response
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Print the response
echo $response;

In this PHP script:

  • We set the API endpoint in the $api_url variable.
  • We initialize a cURL session using curl_init() and set options for the request.
  • We execute the request with curl_exec() and store the response.
  • Finally, we print the response to the output.

C#

C# is a versatile programming language often used for building Windows and ASP.NET Core applications. You can use the HttpClient class to make RESTful API calls in C#. Here's a C# example:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        // Define the API endpoint
        string api_url = "https://anyapi.io/api/v1/exchange/convert?apiKey=<YOUR_API_KEY>";

        // Create an HttpClient instance
        using (HttpClient client = new HttpClient())
        {
            // Make a GET request and get the response
            HttpResponseMessage response = await client.GetAsync(api_url);

            // Ensure a successful response
            if (response.IsSuccessStatusCode)
            {
                // Read the response content as a string
                string data = await response.Content.ReadAsStringAsync();

                // Print the response
                Console.WriteLine(data);
            }
            else
            {
                Console.WriteLine("API request failed. Status code: " + response.StatusCode);
            }
        }
    }
}

In this C# example:

  • We define the API endpoint in the api_url variable.
  • We create an instance of the HttpClient class to send HTTP requests.
  • We make a GET request using client.GetAsync() and handle the response accordingly.