🚀 Experience the new and improved APIVoid! Check out what's new

Code Examples & Quick Tips

Here you can check some code examples to make a HTTPS POST API call to an API endpoint, how to set a custom request header for "Content-type" (that must be "application/json"), for "X-API-Key" (your API key), and how to safely handle JSON response.

# Quick example to make the API call:
                          
curl -X POST "https://api.apivoid.com/v2/ip-reputation" \
     -H "Content-Type: application/json" \
     -H "X-API-Key: <your_api_key_here>" \
     -d '{"ip": "93.174.95.106"}'
     
# A more advanced example that saves the json data:

API_ENDPOINT="https://api.apivoid.com/v2/ip-reputation"
API_KEY="<your_api_key_here>"
IP_ADDRESS="93.174.95.106"

curl --request POST "$API_ENDPOINT" \
     --header "Content-Type: application/json" \
     --header "X-API-Key: $API_KEY" \
     --data '{"ip": "'"$IP_ADDRESS"'"}' \
     --write-out "\nHTTP Status: %{http_code}\n" \
     --silent \
     --output response.json

if jq empty response.json 2>/dev/null; then
    echo "API Response (formatted):"
    jq . response.json
else
    echo "Error: Invalid JSON in response."
fi

How to make a HTTPS POST API call in Curl

With Curl it is very quick and easy to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

$apiEndpoint = 'https://api.apivoid.com/v2/ip-reputation';
$requestPayload = ['ip' => '1.2.3.4'];
$apiKey = 'your_api_key_here';

$ch = curl_init($apiEndpoint);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestPayload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-API-Key: ' . $apiKey,
]);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL Error: " . curl_error($ch);
    curl_close($ch);
    return null;
}

$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpStatusCode !== 200) {
    echo "HTTP Request failed with status code: $httpStatusCode\n";
    print_r($response);
    exit;
}

$decodedResponse = json_decode($response, true);

// Check if JSON decoded correctly
if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Invalid JSON data received\n";
    exit;
}

print_r($decodedResponse);

How to make a HTTPS POST API call in PHP 8

With PHP we can use Curl to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

const axios = require('axios');

const apiEndpoint = 'https://api.apivoid.com/v2/ip-reputation';
const requestPayload = { ip: '1.2.3.4' };
const apiKey = 'your_api_key_here';

(async () => {
    try {
        const response = await axios.post(apiEndpoint, requestPayload, {
            headers: {
                'Content-Type': 'application/json',
                'X-API-Key': apiKey
            }
        });

        const data = response.data;

        console.log('Decoded Response:', data);
    } catch (error) {
        if (error.response) {
            // Server responded with a non-2xx status code
            console.error('Error Response Code:', error.response.status);
            console.error('Error Response Body:', error.response.data);
        } else if (error.request) {
            console.error('No response received:', error.request);
        } else {
            console.error('Error:', error.message);
        }
    }
})();

How to make a HTTPS POST API call in NodeJs

With NodeJs we can use Axios to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

import requests
import json

api_endpoint = 'https://api.apivoid.com/v2/ip-reputation'
request_payload = {'ip': '1.2.3.4'}
api_key = 'your_api_key_here'

try:
    response = requests.post(
        api_endpoint,
        json=request_payload,
        headers={
            'Content-Type': 'application/json',
            'X-API-Key': api_key
        }
    )

    # Check if the response is successful
    response.raise_for_status()

    decoded_response = response.json()

    print('Decoded Response:', json.dumps(decoded_response, indent=4))
except requests.exceptions.RequestException as e:
    print('Request Error:', e)
except json.JSONDecodeError:
    print('Invalid JSON data received')

How to make a HTTPS POST API call in Python3

With Python3 we can use Requests to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

require 'net/http'
require 'uri'
require 'json'

api_endpoint = 'https://api.apivoid.com/v2/ip-reputation'
request_payload = { ip: '1.2.3.4' }.to_json
api_key = 'your_api_key_here'

begin
  uri = URI(api_endpoint)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')

  request = Net::HTTP::Post.new(uri.path, { 'Content-Type' => 'application/json', 'X-API-Key' => api_key })
  request.body = request_payload

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    data = JSON.parse(response.body)
    puts 'Decoded Response:'
    puts data
  else
    puts "Error Response Code: #{response.code}"
    puts "Error Response Body: #{response.body}"
  end
rescue => e
  puts "Error: #{e.message}"
end

How to make a HTTPS POST API call in Ruby

With Ruby we can use Net::HTTP to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    apiEndpoint := "https://api.apivoid.com/v2/ip-reputation"
    requestPayload := map[string]string{
        "ip": "1.2.3.4",
    }
    apiKey := "your_api_key_here"

    payloadBytes, err := json.Marshal(requestPayload)
    if err != nil {
        fmt.Printf("Error marshalling JSON: %v\n", err)
        return
    }

    req, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer(payloadBytes))
    if err != nil {
        fmt.Printf("Error creating request: %v\n", err)
        return
    }

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-API-Key", apiKey)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Printf("Error sending request: %v\n", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    if resp.StatusCode == http.StatusOK {
        var data map[string]interface{}
        if err := json.Unmarshal(body, &data); err != nil {
            fmt.Printf("Error decoding JSON response: %v\n", err)
            return
        }
        fmt.Println("Decoded Response:")
        fmt.Println(data)
    } else {
        fmt.Printf("Error Response Code: %d\n", resp.StatusCode)
        fmt.Printf("Error Response Body: %s\n", string(body))
    }
}

How to make a HTTPS POST API call in Go

With Go we can use net/http to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String apiEndpoint = "https://api.apivoid.com/v2/ip-reputation";
        String apiKey = "your_api_key_here";

        Map<String, String> requestPayload = new HashMap<>();
        requestPayload.put("ip", "1.2.3.4");

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonPayload = objectMapper.writeValueAsString(requestPayload);

            HttpClient client = HttpClient.newHttpClient();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiEndpoint))
                    .header("Content-Type", "application/json")
                    .header("X-API-Key", apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                Map<String, Object> responseData = objectMapper.readValue(response.body(), Map.class);
                System.out.println("Decoded Response:");
                System.out.println(responseData);
            } else {
                System.out.println("Error Response Code: " + response.statusCode());
                System.out.println("Error Response Body: " + response.body());
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

How to make a HTTPS POST API call in Java

With Java we can use HttpClient to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string apiEndpoint = "https://api.apivoid.com/v2/ip-reputation";
        string apiKey = "your_api_key_here";

        var requestPayload = new Dictionary<string, string>
        {
            { "ip", "1.2.3.4" }
        };

        try
        {
            using (HttpClient client = new HttpClient())
            {
                string jsonPayload = JsonSerializer.Serialize(requestPayload);

                var request = new HttpRequestMessage(HttpMethod.Post, apiEndpoint)
                {
                    Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json")
                };
                request.Headers.Add("X-API-Key", apiKey);

                HttpResponseMessage response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var responseData = JsonSerializer.Deserialize<Dictionary<string, object>>(responseBody);
                    Console.WriteLine("Decoded Response:");
                    foreach (var kvp in responseData)
                    {
                        Console.WriteLine($"{kvp.Key}: {kvp.Value}");
                    }
                }
                else
                {
                    Console.WriteLine($"Error Response Code: {response.StatusCode}");
                    string errorBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"Error Response Body: {errorBody}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

How to make a HTTPS POST API call in C# (.NET)

With C# we can use HttpClient class to make a HTTPS POST request to our API service. The payload sent is in JSON and also the data received is in JSON, which is carefully decoded and validated.

Start using our API services, it takes just a few minutes

Create your account, pick a subscription plan, and make your first API call instantly with your API key—simple as that!

Get started now