DEV Community

Cover image for How to Make an API Call?
Wanda
Wanda

Posted on • Edited on

How to Make an API Call?

In today's interconnected world, API calls are the backbone of communication between different software systems. They enable applications to access functionality, retrieve data, and perform specific actions by making requests to external services. In this blog post, we'll dive deep into the concept of API calls, explore how they work, and provide you with a step-by-step guide on how to make effective API calls using the free API testing tool——Apidog.

What is an API Call?

An API call, at its core, is the process of a computer program or application making a request to an external service or server through an API (Application Programming Interface). This request is sent to access specific functionality, retrieve data, or perform a particular action. The API call involves sending a request with defined parameters and receiving a response, often in the form of data or a result, from the external service.

How API Calls Work?

An API call is a request sent from a client to a server, asking for some data or action to be performed. The server processes this request and sends back a response, which the client then uses. Let's break down the process:

1. Client Sends a Request:

  • The process begins when a client (such as a web browser, mobile app, or another server) needs to access some data or functionality from another system.
  • The client makes an HTTP request to the server's API endpoint. This request includes details such as:

    • Method: Defines the type of action (e.g., GET to retrieve data, POST to submit data).
    • URL/Endpoint: Specifies where the request is being sent.
    • Headers: May include authentication tokens, content type, etc.
    • Body(optional): Contains data to be sent to the server, often in JSON format.

2. Server Processes the Request:

  • The server receives the API request and processes it based on the information provided.
  • It checks the request details, such as authentication and permissions, to ensure the client has the right to make the request.
  • The server then retrieves the necessary data or performs the requested action.

3. Server Sends a Response:

  • After processing the request, the server sends back a response to the client.
  • The response includes:

    • Status Code: Indicates whether the request was successful (e.g., 200 OK) or if there was an error (e.g., 404 Not Found).
    • Headers: Provide additional information, like the type of data being returned.
    • Body: Contains the actual data requested by the client, often in JSON format.

4. Client Receives and Processes the Response:

  • The client receives the server's response and processes the data.
  • It then displays the information or performs further actions based on the response.

How to Make an API Call with Apidog?

As we have discussed before, Apidog is an all-in-one API development and testing tool. It offers an intuitive UI for making an API call. Let's get started:

Step 1: Launch Apidog

Open Apidog on your desktop if you have downloaded it or just sign in to the Apidog web app. I would recommend downloading the app, as certain features of Apidog may only be available in the desktop version.

Step 2: Create a New Endpoint Request at Apidog

On the Apidog dashboard, Find "Request" on the left panel, and click on "+ New Request" to create a blank endpoint request panel for making an API call.

create new endpoint request at Apidog

Step 3: Add Endpoint Details

On the newly created endpoint request panel, specify the endpoint details by:

  • Set the HTTP method (e.g., GET) and enter the API endpoint URL.

Define endpoint details at Apidog

  • Add any required headers, query parameters, request body, or auth as specified in the specific API documentation.

Tip: When you input the endpoint URL into the URL bar, the parameters in the endpoint path will automatically appear in the request section. So what you need to do is just to complete the required fields.

Step 4: Make an API Call

Click the "Send" button located on the top right to call the API and receive the response.

Make an API call using Apidog

Step 5: Verify the API response

When the API response is returned, Apidog will validate the response, show the status codes, response body and test report in the response section. This helps verify the effectiveness of the endpoints and you can fix the errors before the actual implementation into the real-life applications.

Step 6: Generate Ready-to-use Code

When the endpoint response is verified, you can generate the client codes for direct deployment in your project. Simply click on "</>" and select the framework that matches your project and copy the code for instant usage.

Generate code at Apidog

That's it! This is how you can make an API call successfully using Apidog and generate the out-of-box code for direct deployment.

I bet even if you are not a developer, you can learn how to test an API with Apidog's intuitive dashoboard!

Apidog is a free tool to get started. Try it out yourself!

Make an API Call in a Coding Way

For those who are interested in making an API by simply coding, here are examples of how to make API calls using various programming languages and libraries.

Example 1: Using Fetch API in JavaScript (for Browser Environments)

// Making a GET request to an API
fetch('https://api.example.com/data', {
  method: 'GET', // Method can be GET, POST, PUT, DELETE etc.
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_TOKEN_HERE' // Replace with your token
  }
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok ' + response.statusText);
  }
  return response.json(); // Parse the JSON from the response
})
.then(data => {
  console.log(data); // Handle the response data here
})
.catch(error => {
  console.error('There was a problem with your fetch operation:', error);
}); 
Enter fullscreen mode Exit fullscreen mode

Example 2: Using Axios in JavaScript (Node.js or Browser)

npm install axios
Enter fullscreen mode Exit fullscreen mode

Then you can use the following code:

const axios = require('axios');

axios.get('https://api.example.com/data', {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_TOKEN_HERE'
  }
})
.then(response => {
  console.log(response.data); // Handle the response data here
})
.catch(error => {
  console.error('Error making the request:', error);
});
Enter fullscreen mode Exit fullscreen mode

Example 3: Using Python with Requests Library

First, install the Requests library:

pip install requests
Enter fullscreen mode Exit fullscreen mode

Then use this code:

import requests

url = 'https://api.example.com/data'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_TOKEN_HERE'
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    data = response.json()  # Parse JSON response
    print(data)  # Handle the response data here
else:
    print(f'Error: {response.status_code} - {response.text}')
Enter fullscreen mode Exit fullscreen mode

Example 4: Using cURL in the Command Line

You can make API calls directly from your command line using cURL:

curl -X GET 'https://api.example.com/data' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_TOKEN_HERE'
Enter fullscreen mode Exit fullscreen mode

Example 5: Using Java with HttpURLConnection

Here's how you can make a GET request using HttpURLConnection in Java:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiCallExample {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://api.example.com/data");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", "Bearer YOUR_API_TOKEN_HERE");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // Print result
                System.out.println(response.toString());
            } else {
                System.out.println("GET request not worked, response code: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

These examples provide a basic overview of how to make API calls using different programming languages and tools. Ensure that you replace the URL and any tokens or parameters specific to your API's requirements. Always read the API's documentation for the correct endpoint URLs, methods, and parameters needed for your requests.

If you want to improve work efficiency, I suggest that you make good use of Apidog.

Let me know whether you try it out on the comment section!

Top comments (0)