---
updatedAt: 2025-05-08T22:49:54.000Z
agentTools:
  projectIndex: https://docs.nanonets.com/llms.txt
---

# Prediction for image file

Nanonets API to upload files to your OCR model in sync mode and to make predictions based on the uploaded images or documents using the file path hosted locally on your system. You can specify multiple file path, this endpoint is optimized for files containing 3 pages or fewer.

***

You can test this API on this page using the API key. First, generate the API key, upload the file stored locally on your system, and enter the `model_id` in the parameter boxes below. Once you have added all the parameters, hit the **“Try It!”** button on the right side panel to see the response in the response box on the right side panel.

***

**Attributes:**

* `message:`This indicates the overall success of the API call.
* `result:`  This is a list that contains objects, each representing a page of the file. These objects include the following attributes:
  * `message`: This indicates the success of page processed in the file.
  * `input`: This is the name of the file uploaded to the model using this API.
  * `prediction`: An array of objects containing detailed predictions for fields and tables identified on the page.\
    **Child Attributes:**
    * `id`: This is the unique identifier for the prediction.
    * `label`: The label name, which corresponds to the field or table header as configured in the model.
    * `xmin`, `ymin`, `xmax`, `ymax`: This represents the minimum and maximum x,y-coordinate of the bounding box used to predict the value for the specified label.
    * `score`: A confidence score in prediction represents the model's certainty in its output. It's a numerical value, usually between 0 and 1, indicating the probability that the prediction is correct. A higher score means greater confidence in the prediction's accuracy.
    * `ocr_text`: This is the predicted value associated with the label
    * `type`: This represent if the label is field or table header. Possible values are field and table.
    * `status`: This field represent the status of the label predicted, it’s always correctly\_predicted.
    * `validation_status`: This indicates the outcome determined by the rule set in the approval rules. If this field is absent from the response for a label, it indicates that the approval rules passed successfully. However, if this field is present and shows "failed," it signifies that the approval rules did not pass.
    * `validation_message`: This indicates the specific reason why a label validation failed. This reason corresponds directly to the rule that was set up in the approval rules.
    * `page_no`: The page number in the document where the label is located, with 0 representing the first page and so on.
    * `label_id`: A unique identifier associated with each label as defined in the model.
    * `cells`: An array of cell predictions within the identified table.\
      **Child Attributes:**
      * `id`: This is the unique identifier for the cell prediction.
      * `row`, `col`: This represent the row and column numbers where the cell is located.
      * `label`: The label name, which corresponds to the table header as configured in the model.
      * `xmin`, `ymin`, `xmax`, `ymax`: This represents the minimum and maximum x,y-coordinate of the bounding box used to predict the value for the specified label.
      * `score`: A confidence score in prediction represents the model's certainty in its output. It's a numerical value, usually between 0 and 1, indicating the probability that the prediction is correct. A higher score means greater confidence in the prediction's accuracy.
      * `text` : This represent the predicted value associated with the cell within the table.
      * `verification_status`: This represent the status of the prediction.
      * `status`: This indicates the outcome based on the rule set in the approval rules. If this field is blank or null, it means the approval rules passed successfully. If it shows "failed," it indicates that the approval rules did not pass.
      * `failed_validation`: This indicates the specific reason why a cell's validation failed. This reason corresponds directly to the rule that was set up in the approval rules.
      * `label_id`: A unique identifier associated with each label as defined in the model.
  * `page`: The page number in the document where the label/table headers are located, with 0 representing the first page and so on.
  * `request_file_id`: The unique identifier of the file you uploaded to the model for prediction. You can find this ID on the extract data page of the model for each file.
  * `id`: This represents the unique identification of the page processed.
  * `request_metadata`: This is a body parameter that you include in the request when making an API call. It is returned in the API response and is typically used to uniquely identify and map the file you uploaded.
  * `processing_type`: This indicates how the file was processed, specifying whether it was handled async or sync. If this field in the response is empty, it means the file was processed sync. If it shows "async," the file was processed async. For more details on sync and async processing, please refer to this page.
  * `size`: This represent the dimension of the pages processed.
    * `width`: This field represent the width of the page
    * `height`: This field represent the height of the page
* `signed_urls`: An object containing signed URLs for accessing various processed files. The original expiry urls are valid for 4 hrs and original with long expiry urls are valid for 180 days.

***

# OpenAPI definition

```json
{
  "openapi": "3.0.1",
  "info": {
    "title": "NanoNets",
    "description": "Welcome to the NanoNets API! You can use our API to build custom deep learning models.<br/>\nWe have language bindings in Shell, Ruby, Golang, Java, C# and Python. You can view code examples in the dark area to the right, and you can switch the programming language for the examples with the tabs in the top right. <br/> In the documentation, you will find ready to fire code samples in these languages as well as detailed API specs for different endpoints.<br/><br/><br/>\n\n### <span style=\"vertical-align: middle;\">Want to quickly test our APIs? &nbsp;</span> <a style=\"vertical-align: middle; display: inline-flex;\" href=\"https://elements.getpostman.com/redirect?entityId=4900737-80d490dc-a342-43be-8160-c9b5bab3c629&entityType=collection\" target=\"_blank\"><img src=\"https://run.pstmn.io/button.svg\" alt=\"Run in Postman\" /></a><br/><br/>\nHelpful links to get you started:<br/><br/>\n**Postman collection variables** - <a href=\"https://learning.postman.com/docs/postman/variables-and-environments/variables/#defining-collection-variables\" target=\"_blank\">https://learning.postman.com/docs/postman/variables-and-environments/variables/#defining-collection-variables</a><br/><br/>\n**To get your API key** <a href=\"https://app.nanonets.com/#keys\" target=\"_blank\">follow this link.</a><br/><br/>\n\n# Model Object\nA model Object has 3 main attributes<br/>\n### model_id\n<b>Definition:</b> Unique ID for the model <br/><br/>\n### model_type\n<b>Definition:</b> Type of model. Possible values are: <br/>\n<table>\n    <tr>\n        <td>classification</td>\n        <td>Image classification model</td>\n    </tr>\n    <tr>\n        <td>ocr</td>\n        <td>OCR model</td>\n    </tr>\n</table> <br/>\n\n### state\n<b>Definition:</b> Current state of model. Possible values are:<br/>\n<table>\n    <tr>\n        <td>-1</td>\n        <td>Error in model training</td>\n    </tr>\n    <tr>\n        <td>0</td>\n        <td>Model created. No training data uploaded yet</td>\n    </tr>\n    <tr>\n        <td>1</td>\n        <td>Training data uploaded. Need to annotate data</td>\n    </tr>\n    <tr>\n        <td>2</td>\n        <td>Training data annotated. Need to start training</td>\n    </tr>\n    <tr>\n        <td>3</td>\n        <td>Model in training queue</td>\n    </tr>\n    <tr>\n        <td>4</td>\n        <td>Model currently training</td>\n    </tr>\n    <tr>\n        <td>5</td>\n        <td>Model hosted. Can be used for prediction</td>\n    </tr>\n    <tr>\n        <td>6</td>\n        <td>Model is retraining with new data. Can be used for prediction</td>\n    </tr>\n</table>\n",
    "contact": {
      "name": "NanoNets",
      "url": "https://nanonets.com",
      "email": "support@nanonets.com"
    },
    "license": {
      "name": "MIT",
      "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT"
    },
    "version": "2.0.0",
    "x-logo": {
      "url": "https://nanonets.com/logo2.png"
    }
  },
  "servers": [
    {
      "url": "https://app.nanonets.com/api/v2"
    }
  ],
  "paths": {
    "/OCR/Model/{model_id}/LabelFile/": {
      "post": {
        "tags": [
          "OCR Predict"
        ],
        "summary": "Prediction for image file",
        "description": "Nanonets API to upload files to your OCR model in sync mode and to make predictions based on the uploaded images or documents using the file path hosted locally on your system. You can specify multiple file path, this endpoint is optimized for files containing 3 pages or fewer.",
        "operationId": "OCRModelLabelFileByModelIdPost",
        "parameters": [
          {
            "name": "model_id",
            "in": "path",
            "description": "Unique identifier for the model to be used for prediction or to fetch predictions.",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "l",
            "in": "query",
            "description": "Represents the most common ISO language codes. Not specifying a language generally yields the best results.",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "multipart/form-data": {
              "schema": {
                "required": [
                  "file"
                ],
                "type": "object",
                "properties": {
                  "file": {
                    "type": "string",
                    "description": "Path of the file stored locally on your system.",
                    "format": "binary"
                  },
                  "base64_data": {
                    "type": "string",
                    "description": "Base64 encoded version of the file urls, which can be sourced locally or from publicly available URLs."
                  },
                  "request_metadata": {
                    "type": "string",
                    "description": "metadata to save with the document"
                  },
                  "pages_to_process": {
                    "type": "string",
                    "description": "Comma-separated page numbers specifying which pages in the document need processing, e.g., '1,2'."
                  }
                }
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "Model Object",
            "content": {
              "application/json": {
                "example": {
                  "message": "Success",
                  "result": [
                    {
                      "message": "Success",
                      "input": "string",
                      "prediction": [
                        {
                          "label": "category1",
                          "xmin": 0,
                          "ymin": 0,
                          "xmax": 100,
                          "ymax": 100,
                          "score": 0.9,
                          "ocr_text": "string"
                        },
                        {
                          "label": "",
                          "ocr_text": "table 1",
                          "type": "table",
                          "score": 99.99,
                          "xmin": 159,
                          "xmax": 380,
                          "ymin": 1258,
                          "ymax": 1439,
                          "cells": [
                            {
                              "row": 1,
                              "col": 1,
                              "row_span": 1,
                              "col_span": 1,
                              "label": "col 1",
                              "xmin": 159,
                              "ymin": 1258,
                              "xmax": 258,
                              "ymax": 1357,
                              "score": 99.99,
                              "text": "ocr text 1"
                            },
                            {
                              "row": 1,
                              "col": 2,
                              "row_span": 1,
                              "col_span": 1,
                              "label": "col 2",
                              "xmin": 258,
                              "ymin": 1258,
                              "xmax": 380,
                              "ymax": 1357,
                              "score": 99.99,
                              "text": "ocr text 2"
                            },
                            {
                              "row": 2,
                              "col": 1,
                              "row_span": 1,
                              "col_span": 1,
                              "label": "col 1",
                              "xmin": 159,
                              "ymin": 1357,
                              "xmax": 258,
                              "ymax": 1439,
                              "score": 99.99,
                              "text": "ocr text 3"
                            },
                            {
                              "row": 2,
                              "col": 2,
                              "row_span": 1,
                              "col_span": 1,
                              "label": "col 2",
                              "xmin": 258,
                              "ymin": 1357,
                              "xmax": 380,
                              "ymax": 1439,
                              "score": 99.99902,
                              "text": "ocr text 4"
                            }
                          ]
                        }
                      ]
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "File missing. Check if you have included a file in the request\n\nOR\n\nIncorrect image. Check if file you included is a valid PNG or JPEG",
            "content": {}
          },
          "402": {
            "description": "Exhausted Free API Calls. You have exhausted your free API calls please change your plan <a href=\"https://app.nanonets.com/user/apps\">here</a>",
            "content": {}
          },
          "404": {
            "description": "Model does not exists. Check if the model id exists",
            "content": {}
          }
        },
        "security": [
          {
            "ApiKey": []
          }
        ],
        "x-unitTests": [],
        "x-operation-settings": {
          "CollectParameters": false,
          "AllowDynamicQueryParameters": false,
          "AllowDynamicFormParameters": false,
          "IsMultiContentStreaming": false
        },
        "x-code-samples": [
          {
            "lang": "Nodejs",
            "source": "var request = require('request')\nvar fs = require('fs')\nconst form_data = {'modelId' : 'REPLACE_MODEL_ID', \n                    'file' : fs.createReadStream('REPLACE_IMAGE_PATH.jpg'),\n                    // for base64 of file instead of file\n                    //'base64_data' : fs.readFileSync(\"REPLACE_IMAGE_PATH.jpg\").toString('base64')\n                  }\n\nconst options = {\n    url : 'https://app.nanonets.com/api/v2/OCR/Model/REPLACE_MODEL_ID/LabelFile/',\n    formData: form_data,\n    headers: {\n        'Authorization' : 'Basic ' + Buffer.from('[[.ApiKey]]' + ':').toString('base64')\n    }\n}\nrequest.post(options, function(err, httpResponse, body) {\n\n  console.log(body)\n});\n"
          },
          {
            "lang": "Python",
            "source": "import requests\n\nurl = 'https://app.nanonets.com/api/v2/OCR/Model/REPLACE_MODEL_ID/LabelFile/'\n\ndata = {'file': open('REPLACE_IMAGE_PATH.jpg', 'rb')}\n\nresponse = requests.post(url, auth=requests.auth.HTTPBasicAuth('[[.ApiKey]]', ''), files=data)\n# for base64 of file instead of file\n# with open('REPLACE_IMAGE_PATH.jpg', 'rb') as file:\n#   encoded_file = base64.b64encode(file.read())\n# data = {'base64_data': encoded_file}\n# response = requests.post(url, auth=requests.auth.HTTPBasicAuth('[[.ApiKey]]', ''), data=data)\n\nprint(response.text)\n"
          },
          {
            "lang": "Shell",
            "source": "curl --request POST \\\n    --url 'https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/' \\\n    --header 'accept: multipart/form-data' \\\n    -u '[[.ApiKey]]' \\\n    -F 'file=@REPLACE_IMAGE_PATH.jpg'\n    # -d 'base64_data=base64OfFile' # for base64 of file instead of file\n"
          },
          {
            "lang": "Golang",
            "source": "package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\"\n    \"io/ioutil\"\n    \"mime/multipart\"\n    \"net/http\"\n    // \"net/url\"\n    \"os\"\n    \"path/filepath\"\n)\n\nfunc main() {\n\n    url := \"https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/\"\n\n    file, err := os.Open(\"REPLACE_IMAGE_PATH.jpg\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    defer file.Close()\n\n    body := &bytes.Buffer{}\n    writer := multipart.NewWriter(body)\n\n    part, err := writer.CreateFormFile(\"file\", filepath.Base(\"REPLACE_IMAGE_PATH.jpg\"))\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    _, err = io.Copy(part, file)\n\n    contentType := writer.FormDataContentType()\n\n    err = writer.Close()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n\n    req, _ := http.NewRequest(\"POST\", url, body)\n\n    // for base64 of file instead of file\n    // data := url.Values{}\n    // data.Add(\"base64_data\", base64OfFile)\n    // req, _ := http.NewRequest(\"POST\", url, bytes.NewBufferString(data.Encode()))\n\n    req.Header.Add(\"Content-Type\", contentType)\n    req.SetBasicAuth(\"[[.ApiKey]]\", \"\")\n\n    res, _ := http.DefaultClient.Do(req)\n\n    defer res.Body.Close()\n    respBody, _ := ioutil.ReadAll(res.Body)\n\n    fmt.Println(res)\n    fmt.Println(string(respBody))\n\n}\n"
          },
          {
            "lang": "JavaScript",
            "source": "var data = new FormData();\ndata.append('file', fileBLob); // This is file object\n//data.append('base64_data', base64EncodedFile); // Can use this for base64 of the file\n\n\nvar xhr = new XMLHttpRequest();\n\nxhr.addEventListener(\"readystatechange\", function () {\n    if (this.readyState === this.DONE) {\n        console.log(this.responseText);\n    }\n});\n\nxhr.open(\"POST\", \"https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/\");\nxhr.setRequestHeader(\"authorization\", \"Basic \" + btoa(\"[[.ApiKey]]:\"));\n\nxhr.send(data);\n"
          },
          {
            "lang": "Ruby",
            "source": "require 'uri'\nrequire 'net/http'\nrequire 'net/http/post/multipart'\n\nurl = URI('https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/')\n\nhttp = Net::HTTP.new(url.host, url.port)\nhttp.use_ssl = true\n\nFile.open('test.jpg') do |jpg|\nrequest = Net::HTTP::Post::Multipart.new(url.path,\n    'file' => UploadIO.new(jpg, 'image/jpeg', 'test.jpg'))\n# for base64 of file instead of file\n# request = Net::HTTP::Post.new(url)\n# request.set_form_data({'base64_data' => base64OfFile})\nrequest.basic_auth '[[.ApiKey]]', ''\nresponse = Net::HTTP.start(url.host, url.port) do |http|\n    http.request(request)\nend\nputs response.read_body\nend\n"
          },
          {
            "lang": "C#",
            "source": "var client = new RestClient(\"https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/\");\nvar request = new RestRequest(Method.POST);\nrequest.AddHeader(\"authorization\", \"Basic \" + Convert.ToBase64String(Encoding.Default.GetBytes(\"[[.ApiKey]]:\")));\nrequest.AddHeader(\"accept\", \"Multipart/form-data\");\nrequest.AddFile(\"file\", \"REPLACE_IMAGE_PATH.jpg\");\n// for base64 of file instead of file\n// request.AddParameter(\"base64_data\", base64OfFile);\nIRestResponse response = client.Execute(request);\n"
          },
          {
            "lang": "Java",
            "source": "OkHttpClient client = new OkHttpClient();\nprivate static final MediaType MEDIA_TYPE_JPG = MediaType.parse(\"image/jpeg\");\n\nOkHttpClient client = new OkHttpClient();\n\nRequestBody requestBody = new MultipartBody.Builder()\n        .setType(MultipartBody.FORM)\n        .addFormDataPart(\"file\", \"REPLACE_IMAGE_PATH.jpg\", RequestBody.create(MEDIA_TYPE_JPG, new File(\"REPLACE_IMAGE_PATH.jpg\")))\n        .build();\n\n# for base64 of file instead of file\n# RequestBody formBody = new FormBody.Builder()\n#         .add(\"base64_data\", base64OfFile).build();\nrequest = new Request.Builder()\n        .url(\"https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/\")\n        .post(requestBody)\n        .addHeader(\"Authorization\", Credentials.basic(\"[[.ApiKey]]\", \"\"))\n        .build();\n\nResponse response = client.newCall(request).execute();\n"
          }
        ]
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKey": {
        "type": "http",
        "description": "When you sign up for an account, you are given your first API key. To do so please [follow this link.](https://app.nanonets.com/#keys)\n\nAlso you can generate additional API keys, and delete API keys (as you may need to rotate your keys in the future). NanoNets expects for the API key to be included in all API requests to the server in a header that looks like the following:\n\n<span style=\"color:red\">Authorization: [[.ApiKey]]</span>\n\nAll API requests must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.",
        "scheme": "basic",
        "x-testValue": [],
        "x-skip-client-authentication": false
      }
    }
  },
  "x-tagGroups": [
    {
      "name": "OCR",
      "tags": [
        "OCR Model",
        "OCR Upload",
        "OCR Train",
        "OCR Predict"
      ]
    },
    {
      "name": "Free Full Text OCR",
      "tags": [
        "Get Full Text"
      ]
    },
    {
      "name": "Image Classification",
      "tags": [
        "Image Classification Model",
        "Image Classification Model Upload",
        "Image Classification Model Train",
        "Image Classification Model Predict"
      ]
    }
  ],
  "x-original-swagger-version": "2.0",
  "x-readme": {
    "explorer-enabled": true,
    "proxy-enabled": true
  }
}
```