File Checker API

The File Check API allows you to upload a file and check it against known malware, viruses, and other types of malicious content. This API utilizes both signature-based and behavior-based detection techniques to ensure a comprehensive analysis.

How to use?

You need to use the POST request with the file data and your API key. The request should be formatted as 'multipart/form-data'.

POST https://inspector.gridinsoft.com/api/v1/file/check

Request:

Field Type Description
apikey String Your unique API key that authenticates requests to our services.
file File The file to be checked, uploaded as multipart/form-data.

Example:

curl -X POST https://inspector.gridinsoft.com/api/v1/file/check \
     -H 'Content-Type: multipart/form-data' \
     -F 'apikey=YOUR_PRIVATE_APIKEY' \
     -F 'file=@/path/to/your/file'

Response:

Field Type Description
sha256 String SHA-256 hash of the file.
md5 String MD5 hash of the file.
filename String Name of the file.
size Integer Size of the file in bytes.
detection String Detected malware or threat category, if any.
type String Description of the file type.
heuristic Object Heuristic analysis indicates whether the file is malicious or harmless. For premium users, detailed analysis is available, highlighting signs of suspicion.
PE Object PE data in an executable (EXE) file refers to the Portable Executable format, which is a file format for executables, object code, DLLs, FON Font files, and others used in 32-bit and 64-bit versions of Windows operating systems. Available for paid plans

For programming languages

Using one of these samples is the easiest way to start using our API. Feel free to add additional functionalities as needed.


import requests

def send_file_for_check(api_key, file_path, url):
    if not os.path.exists(file_path):
        print("File does not exist:", file_path)
        return

    with open(file_path, 'rb') as f:
        files = {'file': f}
        data = {'apikey': api_key}
        response = requests.post(url, files=files, data=data)

    try:
        response.raise_for_status()
        print("File checked successfully:", response.json())
    except requests.RequestException as e:
        print("Error during file check:", str(e))

# Example usage:
api_key = 'YOUR_PRIVATE_APIKEY'
file_path = '/path/to/your/file.exe'
url = 'https://inspector.gridinsoft.com/api/v1/file/check'
send_file_for_check(api_key, file_path, url)

function Send-FileForCheck {
    param(
        [string]$filePath,
        [string]$apiKey,
        [string]$url = "https://inspector.gridinsoft.com/api/v1/file/check"
    )

    if (-not (Test-Path $filePath)) {
        Write-Host "File does not exist: $filePath" -ForegroundColor Red
        return
    }

    $boundary = [System.Guid]::NewGuid().ToString()
    $LF = "`r`n"

    $headers = @{
        "Content-Type" = "multipart/form-data; boundary=`"$boundary`""
    }

    $bodyLines = (
        "--$boundary",
        'Content-Disposition: form-data; name="file"; filename="{0}"' -f [System.IO.Path]::GetFileName($filePath),
        "Content-Type: application/octet-stream$LF",
        [System.IO.File]::ReadAllBytes($filePath),
        "--$boundary",
        'Content-Disposition: form-data; name="apikey"$LF',
        "$apiKey",
        "--$boundary--$LF"
    ) -join $LF

    $bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($bodyLines)

    try {
        $response = Invoke-RestMethod -Uri $url -Method Post -Headers $headers -Body $bodyBytes -ContentType $headers["Content-Type"]
        Write-Host "File checked successfully. Response:" -ForegroundColor Green
        Write-Host ($response | ConvertTo-Json)
    }
    catch {
        Write-Host "Error during file check: $_" -ForegroundColor Red
    }
}

# Example usage:
$filePath = "C:\path\to\your\file.exe"
$apiKey = "YOUR_PRIVATE_APIKEY"
Send-FileForCheck -filePath $filePath -apiKey $apiKey

async function sendFileForCheck(apiKey, filePath, url) {
    if (!filePath.files[0]) {
        console.error("File does not exist");
        return;
    }

    let formData = new FormData();
    formData.append('file', filePath.files[0]);
    formData.append('apikey', apiKey);

    try {
        let response = await fetch(url, {
            method: 'POST',
            body: formData
        });

        if (!response.ok) throw new Error('Server responded with ' + response.status);
        let data = await response.json();
        console.log("File checked successfully:", data);
    } catch (error) {
        console.error("Error during file check:", error.message);
    }
}

// Example usage:
document.getElementById('fileUploadForm').addEventListener('submit', function(event) {
    event.preventDefault();
    const apiKey = 'YOUR_PRIVATE_APIKEY';
    const fileInput = document.getElementById('fileInput');
    const url = 'https://inspector.gridinsoft.com/api/v1/file/check';
    sendFileForCheck(apiKey, fileInput, url);
});


import okhttp3.*
import java.io.File

fun sendFileForCheck(apiKey: String, filePath: String, url: String) {
    val file = File(filePath)
    if (!file.exists()) {
        println("File does not exist: $filePath")
        return
    }

    val client = OkHttpClient()
    val requestBody = MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", file.name,
            RequestBody.create(MediaType.parse("application/octet-stream"), file))
        .addFormDataPart("apikey", apiKey)
        .build()

    val request = Request.Builder()
        .url(url)
        .post(requestBody)
        .build()

    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) {
            println("Error during file check: ${response.message}")
            return
        }

        println("File checked successfully: ${response.body?.string()}")
    }
}

fun main() {
    val apiKey = "YOUR_PRIVATE_APIKEY"  // Replace with your API key
    val filePath = "/path/to/your/file.exe"  // Path to the file you want to check
    val url = "https://inspector.gridinsoft.com/api/v1/file/check"  // API endpoint

    sendFileForCheck(apiKey, filePath, url)
}

  • File Handling: The script checks if the file exists before trying to upload it.
  • OkHttp: This library is used for making HTTP requests. The `MultipartBody.Builder` is used to construct the multipart request containing the file and other form data.
  • Error Handling: The response from the server is checked. If the HTTP response is not successful, an error message is printed.
  • Reading Response: The response body is printed if the request is successful. Note that `response.body?.string()` should only be called once as it consumes the response stream

package main

import (
    "bytes"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "os"
)

func sendFileForCheck(apiKey, filePath, url string) {
    file, err := os.Open(filePath)
    if err != nil {
        fmt.Println("File does not exist:", err)
        return
    }
    defer file.Close()

    var requestBody bytes.Buffer
    writer := multipart.NewWriter(&requestBody)
    part, err := writer.CreateFormFile("file", filePath)
    if err != nil {
        fmt.Println("Error creating form file:", err)
        return
    }
    _, err = io.Copy(part, file)
    if err != nil {
        fmt.Println("Error copying file:", err)
        return
    }

    _ = writer.WriteField("apikey", apiKey)
    writer.Close()

    request, err := http.NewRequest("POST", url, &requestBody)
    request.Header.Set("Content-Type", writer.FormDataContentType())

    client := &http.Client{}
    response, err := client.Do(request)
    if err != nil {
        fmt.Println("Error during file check:", err)
        return
    }
    defer response.Body.Close()

    fmt.Println("File checked successfully. Status code:", response.StatusCode)
}

// Example usage:
func main() {
    apiKey := "YOUR_PRIVATE_APIKEY"
    filePath := "/path/to/your/file.exe"
    url := "https://inspector.gridinsoft.com/api/v1/file/check"
    sendFileForCheck(apiKey, filePath, url)
}

#!/bin/bash

api_key="YOUR_PRIVATE_APIKEY"  # Your API Key
file_path="/path/to/your/file.exe"
url="https://inspector.gridinsoft.com/api/v1/file/check"

if [[ ! -f "$file_path" ]]; then
    echo "File does not exist: $file_path"
    exit 1
fi

# Perform the file upload
response=$(curl -s -F "file=@$file_path" -F "apikey=$api_key" "$url")
http_status=$(curl -o /dev/null -s -w "%{http_code}\n" -F "file=@$file_path" -F "apikey=$api_key" "$url")

# Check if the HTTP status code is 200 OK
if [ "$http_status" -eq 200 ]; then
    echo "File checked successfully:"
    echo "$response" | jq '.'
else
    echo "Error during file check: HTTP Status $http_status"
    echo "$response" | jq '.'
fi
  • JSON Parsing: The script uses `jq` to parse the JSON response. Make sure `jq` is installed on your system to use this feature.
  • HTTP Status Codes: It captures the HTTP status code to determine whether the request was successful (`200 OK`) or if there was an error. This helps in determining the appropriate action based on the response code.
  • Output Handling: The script now properly separates the response handling and error messages, improving the readability and user experience when interacting with the script.

Ruby's standard library includes `net/http`, which is suitable for making HTTP requests.


require 'rest-client'
require 'json'

def send_file_for_check(api_key, file_path, url)
  unless File.exist?(file_path)
    puts "File does not exist: #{file_path}"
    return
  end

  begin
    response = RestClient.post(url,
                               { file: File.new(file_path, 'rb'),
                                 apikey: api_key },
                               { content_type: 'multipart/form-data' })
    result = JSON.parse(response.body)
    puts "File checked successfully: #{result}"
  rescue RestClient::ExceptionWithResponse => e
    puts "Error during file check: #{e.response}"
  rescue => e
    puts "Error: #{e.message}"
  end
end

# Example usage
api_key = 'YOUR_PRIVATE_APIKEY'  # Your API Key
file_path = '/path/to/your/file.exe'  # Path to the file you want to check
url = 'https://inspector.gridinsoft.com/api/v1/file/check'  # API endpoint

send_file_for_check(api_key, file_path, url)
  • File Existence Check: The script checks if the file exists before attempting to send it.
  • Sending the File: The `RestClient.post` method is used to send the file along with other data. The file is opened and sent as part of the multipart form data.
  • Error Handling: Errors during the HTTP request are caught and handled. `RestClient::ExceptionWithResponse` captures HTTP-related errors, providing access to the response object.
  • Response Parsing: The response is expected to be in JSON format, which is parsed and printed to the console.

function sendFileForCheck($apiKey, $filePath, $url) {
    if (!file_exists($filePath)) {
        echo "File does not exist: $filePath";
        return;
    }

    $file = new CURLFile($filePath);
    $data = ['file' => $file, 'apikey' => $apiKey];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        echo "Error during file check: " . curl_error($ch);
    } else {
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode == 200) {
            echo "File checked successfully: " . $response;
        } else {
            echo "Failed to check file, HTTP Status Code: " . $httpCode;
        }
    }
    curl_close($ch);
}

// Example usage:
$apiKey = 'YOUR_PRIVATE_APIKEY'; // Your API key
$filePath = '/path/to/your/file.exe'; // Change this path to your file path
$url = 'https://inspector.gridinsoft.com/api/v1/file/check';
sendFileForCheck($apiKey, $filePath, $url);

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

class Program
{
    static async Task Main(string[] args)
    {
        string apiKey = "YOUR_PRIVATE_APIKEY"; // Your API Key
        string filePath = "/path/to/your/file.exe"; // Path to the file you want to check
        string url = "https://inspector.gridinsoft.com/api/v1/file/check"; // API endpoint

        try
        {
            await SendFileForCheck(apiKey, filePath, url);
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    static async Task SendFileForCheck(string apiKey, string filePath, string url)
    {
        if (!File.Exists(filePath))
        {
            Console.WriteLine("File does not exist: " + filePath);
            return;
        }

        using (var httpClient = new HttpClient())
        using (var form = new MultipartFormDataContent())
        {
            // Add file content to the form
            var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
            fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
            form.Add(fileContent, "file", Path.GetFileName(filePath));

            // Add API key to the form
            form.Add(new StringContent(apiKey), "apikey");

            // Post the data to the specified URL
            var response = await httpClient.PostAsync(url, form);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("File checked successfully: " + responseBody);
            }
            else
            {
                Console.WriteLine($"Error during file check: {response.StatusCode} {await response.Content.ReadAsStringAsync()}");
            }
        }
    }
}
  • HttpClient: This class is used for making HTTP requests in .NET.
  • MultipartFormDataContent: This class is used to construct multipart/form-data content which is necessary for file uploads.
  • Async/Await: The method `SendFileForCheck` is asynchronous, which helps in performing non-blocking network requests.

#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <cpprest/http_listener.h>              // HTTP server
#include <cpprest/json.h>                       // JSON library
#include <cpprest/uri.h>                        // URI library
#include <cpprest/asyncrt_utils.h>              // Utilities
#include <iostream>
#include <fstream>

using namespace utility;                        // Common utilities like string conversions
using namespace web;                            // Common features like URIs.
using namespace web::http;                      // Common HTTP functionality
using namespace web::http::client;              // HTTP client features
using namespace concurrency::streams;           // Asynchronous streams

void send_file_for_check(const std::string& api_key, const std::string& file_path, const std::string& url) {
    // Open stream to file.
    auto fileStream = std::make_shared<istream>();
    auto file = std::make_shared<streambuf<uint8_t>>();
    fstream::open_istream(file_path, *file).then([=](const istream&) {
        *fileStream = istream(file);

        // Create HTTP client to send the request.
        http_client client(U(url));
        http_request request(methods::POST);

        // Create multipart form data content.
        auto form = new multipart_form_data_content();
        form->add(istream_body(file_path.substr(file_path.find_last_of("/\\") + 1), *fileStream), U("file"), U("application/octet-stream"));
        form->add({api_key}, U("apikey"));

        // Set request body and headers.
        request.set_body(form);
        request.headers().set_content_type(form->content_type());

        // Send the request.
        return client.request(request);
    }).then([](http_response response) {
        // Check the status code.
        if (response.status_code() == status_codes::OK) {
            return response.extract_json();
        } else {
            std::cout << "HTTP request failed with status code " << response.status_code() << std::endl;
            return pplx::task_from_result(json::value());
        }
    }).then([](json::value jsonResponse) {
        // Process the JSON response.
        std::wcout << U("File checked successfully: ") << jsonResponse.serialize() << std::endl;
    }).wait();
}

int main() {
    std::string api_key = "YOUR_PRIVATE_APIKEY";  // Your API key
    std::string file_path = "/path/to/your/file.exe";  // Path to your file
    std::string url = "https://inspector.gridinsoft.com/api/v1/file/check";  // API endpoint

    send_file_for_check(api_key, file_path, url);

    return 0;
}

  • File Handling: The file is opened as a stream, which is then attached to the HTTP request.
  • HTTP Client: `http_client` is used to send POST requests.
  • Error Handling: Proper error checking ensures that any HTTP errors are reported.
  • Response Processing: The response is expected to be JSON and is printed out.

import java.io.*;
import java.net.URI;
import java.net.http.*;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.json.JSONObject;

public class FileChecker {
    private static final String API_KEY = "YOUR_PRIVATE_APIKEY";  // Your API Key
    private static final String URL = "https://inspector.gridinsoft.com/api/v1/file/check";

    public static void Check(String apiKey, String filePath, String url) {
        if (!Files.exists(Paths.get(filePath))) {
            System.out.println("File does not exist: " + filePath);
            return;
        }

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest.BodyPublisher bodyPublisher = BodyPublishers.ofFile(Paths.get(filePath));
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "multipart/form-data")
                .POST(bodyPublisher)
                .build();

        try {
            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
            JSONObject jsonResponse = new JSONObject(response.body());
            System.out.println("File checked successfully: " + jsonResponse.toString());
        } catch (Exception e) {
            System.out.println("Error during file check: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String filePath = "/path/to/your/file.exe";  // Update the file path as needed
        Check(API_KEY, filePath, URL);
    }
}

To implement the domain check function in Rust, you can use the `reqwest` crate for making HTTP requests.

Before you begin, ensure these crates are added to your `Cargo.toml`:


[dependencies]
reqwest = { version = "0.11", features = ["json", "multipart"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"

use reqwest::Client;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use std::path::Path;
use anyhow::Result;

async fn send_file_for_check(api_key: &str, file_path: &str, url: &str) -> Result<()> {
    if !Path::new(file_path).exists() {
        println!("File does not exist: {}", file_path);
        return Ok(());
    }

    let mut file = File::open(file_path).await?;
    let mut contents = Vec::new();
    file.read_to_end(&mut contents).await?;

    let form = reqwest::multipart::Form::new()
        .part("file", reqwest::multipart::Part::bytes(contents).file_name("file.exe"))
        .text("apikey", api_key.to_string());

    let client = Client::new();
    let response = client.post(url)
        .multipart(form)
        .send()
        .await?;

    if response.status().is_success() {
        let json = response.json::<serde_json::Value>().await?;
        println!("File checked successfully: {:?}", json);
    } else {
        anyhow::bail!("Error during file check: Status code {}", response.status());
    }

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let api_key = "YOUR_PRIVATE_APIKEY"; // Your API Key
    let file_path = "/path/to/your/file.exe"; // Path to the file you want to check
    let url = "https://inspector.gridinsoft.com/api/v1/file/check"; // API endpoint

    send_file_for_check(api_key, file_path, url).await?;

    Ok(())
}

    
  • File Operations: Rust uses `okio::fs` for async file operations. This example reads the entire file into memory, which is suitable for small to medium files.
  • HTTP Requests: Using `reqwest` with `multipart` feature enabled allows sending files as part of a multipart/form-data POST request.
  • Error Handling: The `anyhow` crate is used to provide convenient error handling. Rust's error management requires explicit handling of all possible error conditions.
  • Async Programming: Rust's `async` functions require an executor, here provided by tokio.

import Foundation

func sendFileForCheck(apiKey: String, filePath: String, url: URL) {
    let fileUrl = URL(fileURLWithPath: filePath)
    guard FileManager.default.fileExists(atPath: filePath) else {
        print("File does not exist: \(filePath)")
        return
    }

    // Create the URLRequest object
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    // Generate boundary string using a unique per-app string.
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // Create body
    var body = Data()

    // Add the api key part
    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"apikey\"\r\n\r\n".data(using: .utf8)!)
    body.append("\(apiKey)\r\n".data(using: .utf8)!)

    // Add the file data
    body.append("--\(boundary)\r\n".data(using: .utf8)!)
    body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileUrl.lastPathComponent)\"\r\n".data(using: .utf8)!)
    body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!)
    if let fileData = try? Data(contentsOf: fileUrl) {
        body.append(fileData)
        body.append("\r\n".data(using: .utf8)!)
    }

    body.append("--\(boundary)--\r\n".data(using: .utf8)!)

    // Append body to the request
    request.httpBody = body

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

        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
            if let responseString = String(data: data, encoding: .utf8) {
                print("File checked successfully:", responseString)
            }
        } else {
            print("Error during file check: HTTP \(String(describing: (response as? HTTPURLResponse)?.statusCode))")
        }
    }

    task.resume()
}

// Example usage:
let apiKey = "YOUR_PRIVATE_APIKEY"  // Your API Key
let filePath = "/path/to/your/file.exe"  // Path to the file you want to check
if let url = URL(string: "https://inspector.gridinsoft.com/api/v1/file/check") {
    sendFileForCheck(apiKey: apiKey, filePath: filePath, url: url)
}

  • Multipart Request Creation: Manually creates a multipart form data request including the file data and API key.
  • Networking: Uses `URLSession` to asynchronously send the request.
  • Boundary: Uses a unique boundary string for separating parts of the HTTP body.
Ready to get started?
Sign up to try Inspector API
We use cookies. Cookies help us deliver the best experience on our website. By using our website, you agree to the use of cookies.