Call Azure Form Recognizer Analyze Receipt using Document/Image File URL or Binary Content

This is a quick post showing how to use Azure Form Recognizer API.

Azure Form Recognizer can analyze custom-model form, where we will have to train data to create a model first, or pre-built model, which currently offers only for U.S. sales receipts. Even though this post will only talk about the latter, the same concept applies to the former.

According to API documentation, the Form Recognizer API can be called with the content-type as a path to a file (application/json) or file binary content based on file type (application/pdf, image/jpeg, image/png, or image/tiff).

The Python code sample shows how to call API using the binary content option.

source_file = "contoso-allinone.jpg"

headers = {
    # Request headers
    'Content-Type': 'image/jpeg',
    'Ocp-Apim-Subscription-Key': apim_key,
}

params = {
    "includeTextDetails": True
}

with open(source_file, "rb") as f:
    data_bytes = f.read()

try:
    resp = post(url = post_url, data = data_bytes, headers = headers, params = params)
    if resp.status_code != 202:
        print("POST analyze failed:\n%s" % resp.text)
        quit()
    get_url = resp.headers["operation-location"]
except Exception as e:
    print("POST analyze failed:\n%s" % str(e))
    quit()

We can do the same with the file URL option as seen below. Note the change in the Content-Type header.

headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': apim_key,
}

params = {
    "includeTextDetails": True
}

body = "{\"source\": \"https://docs.microsoft.com/en-us/azure/cognitive-services/form-recognizer/media/contoso-allinone.jpg\"}"

try:
    resp = post(url = post_url, data = body, headers = headers, params = params)
    if resp.status_code != 202:
        print("POST analyze failed:\n%s" % resp.text)
        quit()
    get_url = resp.headers["operation-location"]
except Exception as e:
    print("POST analyze failed:\n%s" % str(e))
    quit()

1 thought on “Call Azure Form Recognizer Analyze Receipt using Document/Image File URL or Binary Content”

  1. Pingback: Call Azure Form Recognizer API on SharePoint document/image URL in Power Automate | Ittichai Chammavanijakul

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top