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

# Async Prediction for image file

Nanonets API to upload files to your OCR model in async 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, ideal for larger files with more than 3 pages.

***

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, set `async = true`, 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:`  A list of objects representing each page of the processed files. 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 empty list, meaning no predictions were made. In the case of async precessing prediction list is empty because in the async processing the file is processed at a later point in time.
  * `page:`The page number in the document where the label is 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 is the unique identifier for the prediction.
  * `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.
* `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": "Async Prediction for image file",
        "description": "Nanonets API to upload files to your OCR model in async 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, ideal for larger files with more than 3 pages.",
        "operationId": "OCRModelLabelFileAsyncByModelIdPost",
        "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": "async",
            "in": "query",
            "description": "Determines whether the file should be processed synchronously or asynchronously. Set to true for asynchronous file processing.",
            "required": true,
            "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."
                  }
                }
              }
            }
          },
          "required": true
        },
        "responses": {
          "200": {
            "description": "message can contain 3 status messages\n1. success - file has been successfully processed\n2. pending - file is in the queue and will be processed\n3. failure - There was an issue while processing the file. It has been retrried 3 times. It is recommended to reupload the file and if the issue persists, please contact support ",
            "content": {
              "application/json": {
                "example": {
                  "message": "Success",
                  "result": [
                    {
                      "message": "Success",
                      "input": "Test_file.pdf",
                      "prediction": [],
                      "page": 0,
                      "request_file_id": "050a1d5d-f973-48c1-8078-d22be2754e86",
                      "filepath": "uploadedfiles/00000000-0000-0000-0000-000000000000/PredictionImages/filename.jpeg",
                      "id": "f78756a0-63d4-11ef-b8d2-ea107f2836f3",
                      "rotation": 0,
                      "file_url": "uploadedfiles/00000000-0000-0000-0000-000000000000/PredictionImages/original_file_name-xxxx.jpeg",
                      "request_metadata": "",
                      "processing_type": "async",
                      "size": {},
                      "raw_ocr_api_response": {
                        "results": null
                      }
                    }
                  ],
                  "signed_urls": {
                    "uploadedfiles/473fd562-382a-4f12-9e81-f1f21bba9401/PredictionImages/b220eeed-bf83-4d4d-87fc-4623b26802de-1.jpeg": {
                      "original": "https://images.nanonets.com/tr:rt-0,true/uploadedfiles/473fd562-382a-4f12-9e81-f1f21bba9401/PredictionImages/b220eeed-bf83-4d4d-87fc-4623b26802de-1.jpeg",
                      "original_with_long_expiry": "https://images.nanonets.com/tr:rt-0,true/uploadedfiles/473fd562-382a-4f12-9e81-f1f21bba9401/PredictionImages/b220eeed-bf83-4d4d-87fc-4623b26802de-1.jpeg?ik-t=1740247181"
                    },
                    "uploadedfiles/473fd562-382a-4f12-9e81-f1f21bba9401/RawPredictions/050a1d5d-f973-48c1-8078-d22be2754e86.pdf": {
                      "original": "https://images.nanonets.com/uploadedfiles/473fd562-382a-4f12-9e81-f1f21bba9401/RawPredictions/050a1d5d-f973-48c1-8078-d22be2754e86.pdf?ik-s=b7b1e08decd0a592f3c017e1446f42179c2b3fc8&ik-t=1724709581"
                    }
                  }
                }
              }
            }
          },
          "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/?async=true',\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/?async=true'\n\ndata = {'file': open('REPLACE_IMAGE_PATH.jpg', 'rb')}\n\nresponse = requests.post(url, auth=requests.auth.HTTPBasicAuth('[[.ApiKey]]', ''), files=data)\n\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/?async=true' \\\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/?async=true\"\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/?async=true\");\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/?async=true')\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/?async=true\");\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();\n\nrequest = new Request.Builder()\n        .url(\"https://app.nanonets.com/api/v2/OCR/Model/{{model_id}}/LabelFile/?async=true\")\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
  }
}
```