Code Snippets

This page provides examples of how to make an API call to the /v1 endpoint of the IP Location API using the most popular programming languages. Each example demonstrates how to send a request with an API key and an IP address to retrieve location information.

cURL

curl -X POST https://api.ip-location-api.com/v1 \
  -H "Content-Type: application/json" \
  -H "apikey: your-api-key-here" \
  -d '{
    "ip": "101.49.50.12"
}'

JavaScript (Node.js)

const fetch = require('node-fetch');

const apiKey = 'your-api-key-here';
const ip = '101.49.50.12';

fetch('https://api.ip-location-api.com/v1', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'apikey': apiKey
  },
  body: JSON.stringify({ ip })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Python

import requests
import json

apiKey = 'your-api-key-here'
ip = '101.49.50.12'
url = 'https://api.ip-location-api.com/v1'

headers = {
    'Content-Type': 'application/json',
    'apikey': apiKey
}

data = {
    'ip': ip
}

response = requests.post(url, headers=headers, data=json.dumps(data))
print(response.json())

Java

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            String apiKey = "your-api-key-here";
            String ip = "101.49.50.12";
            URL url = new URL("https://api.ip-location-api.com/v1");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("apikey", apiKey);
            conn.setDoOutput(true);

            String jsonInputString = "{\"ip\": \"" + ip + "\"}";

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-");
                os.write(input, 0, input.length);
            }

            try (Scanner scanner = new Scanner(conn.getInputStream(), "UTF-")) {
                String response = scanner.useDelimiter("\\A").next();
                System.out.println(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

C#

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

class Program
{
    static async Task Main(string[] args)
    {
        string apiKey = "your-api-key-here";
        string ip = "101.49.50.12";
        string url = "https://api.ip-location-api.com/v1";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("apikey", apiKey);
            var content = new StringContent("{\"ip\":\"" + ip + "\"}", Encoding.UTF, "application/json");

            HttpResponseMessage response = await client.PostAsync(url, content);
            string result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
    }
}

PHP

<?php
$apiKey = "your-api-key-here";
$ip = "101.49.50.12";
$url = "https://api.ip-location-api.com/v1";

$headers = array(
    "Content-Type: application/json",
    "apikey: $apiKey"
);

$data = json_encode(array("ip" => $ip));

$options = array(
    "http" => array(
        "header" => implode("\r\n", $headers),
        "method" => "POST",
        "content" => $data
    )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) {
    die('Error');
}

var_dump($result);
?>

Ruby

require 'net/http'
require 'json'

api_key = 'your-api-key-here'
ip = '101.49.50.12'
url = URI('https://api.ip-location-api.com/v1')

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['Content-Type'] = 'application/json'
request['apikey'] = api_key
request.body = { ip: ip }.to_json

response = http.request(request)
puts response.read_body

Go

package main

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

func main() {
	apiKey := "your-api-key-here"
	ip := "101.49.50.12"
	url := "https://api.ip-location-api.com/v1"

	data := map[string]string{"ip": ip}
	jsonData, _ := json.Marshal(data)

	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("apikey", apiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	json.NewDecoder(resp.Body).Decode(&result)

	fmt.Println(result)
}

Swift

import Foundation

let apiKey = "your-api-key-here"
let ip = "101.49.50.12"
let url = URL(string: "https://api.ip-location-api.com/v1")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(apiKey, forHTTPHeaderField: "apikey")

let json: [String: Any] = ["ip": ip]
let jsonData = try? JSONSerialization.data(withJSONObject: json)

request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("Error:", error ?? "Unknown error")
        return
    }

    if let httpResponse = response as? HTTPURLResponse {
        print("Status code:", httpResponse.statusCode)
    }

    let responseData = try? JSONSerialization.jsonObject(with: data, options: [])
    print(responseData ?? "No response data")
}

task.resume()

Get Started

FeaturesPricingStart a Free Trial
IP Location API Logo

© 2024 IP Location API, LLC. All rights reserved.