Form Recognizer API (v2.1)
Form Recognizer extracts information from forms and images into structured data. It includes the following options:
- Form - Extracts information from forms (PDFs and images) into structured data based on a model created from a set of representative training forms. Form Recognizer learns the structure of your forms to intelligently extract text and data. It ingests text from forms, applies machine learning technology to identify keys, tables, and fields, and then outputs structured data that includes the relationships within the original file.
- Receipt - Detects and extracts data from receipts using optical character recognition (OCR) and our receipt model, enabling you to easily extract structured data from receipts such as merchant name, merchant phone number, transaction date, transaction total, and more.
- Business Card - Detects and extracts data from business cards using optical character recognition (OCR) and our business card model, enabling you to easily extract structured data from business cards such as contact names, company names, phone numbers, emails, and more.
- Layout - Extracts text and table structure from documents using optical character recognition (OCR).
- Invoices - Detects and extracts data from invoices using optical character recognition (OCR) and our invoice understanding deep learning models, enabling you to easily extract structured data from invoices such as customer, vendor, invoice ID, invoice due date, total, invoice amount due, tax amount, ship to, bill to, line items and more.
- ID Documents - Detects and extracts data from identification documents using optical character recognition (OCR) and our ID document model, enabling you to easily extract structured data from ID documents such as first name, last name, date of birth, document number, and more.
Analyze Receipt - Get Analyze Receipt Result
Query the status and retrieve the result of an Analyze Receipt operation. The URL to this interface can be obtained from the 'Operation-Location' header in the Analyze Receipt response. We recommend calling this operation no more than once a second.
Select the testing console in the region where you created your resource:
Australia East Brazil South Canada Central Central India Central US Central US EUAP East Asia East US East US 2 France Central Germany West Central Japan East Japan West Korea Central North Central US North Europe South Africa North South Central US Southeast Asia Switzerland North Switzerland West UAE North UK South West Central US West Europe West US West US 2 West US 3 Norway East Jio India WestRequest URL
Request parameters
string
Format - uuid. Analyze operation result identifier.
Request headers
string
Subscription key which provides access to this API. Found in your Cognitive Services accounts.
Request body
Response 200
JSON fields in the response body:
Field | Type | Description |
---|---|---|
status | String | Analyze Receipt operation status.
Possible values:
|
createdDateTime | String | Date and time (UTC) when the operation was created. |
lastUpdatedDateTime | String | Date and time (UTC) when the status is last updated. |
analyzeResult | Object | Results of the analyze operation. |
readResults | [Object] | List of of extracted text result for each page in the input document. |
lines | [Object] | List of text lines. The lines are sorted top to bottom, left to right, although in certain cases proximity is treated with higher priority. As the sorting order depends on the detected text, it may change across images and OCR version updates. Thus, business logic should be built upon the actual line location instead of order. This field only appears when includeTextDetails is set to true. |
words | [Object] | List of words in the text line. |
boundingBox | [Number] | Quadrangle bounding box of a line or word, depending on the parent object, specified as a list of 8 numbers. The coordinates are specified relative to the top-left of the original image. The eight numbers represent the four points, clockwise from the top-left corner relative to the text orientation. For image, the (x, y) coordinates are measured in pixels. For PDF, the (x, y) coordinates are measured in inches. |
text | String | Extracted field text in documentResults, or the text content of a word/line in readResults. |
confidence | Number | Confidence value. |
width | Number | The width of the image/PDF in pixels/inches, respectively. |
height | Number | The height of the image/PDF in pixels/inches, respectively. |
angle | Number | The general orientation of the text in clockwise direction, measured in degrees between (-180, 180]. |
page | Integer | The 1-based page number in the input document. |
unit | String | The unit used by the width, height and boundingBox properties. For images, the unit is "pixel". For PDF, the unit is "inch". |
language | String | The detected language on the page overall or of a specific line if different from the page. |
version | String | The version of schema used for this result. |
documentResults | [Object] | An array of objects, each representing a receipt detected in the input document. |
docType | String | The value is set to "prebuilt:receipt" to indicate a receipt document. |
pageRange | [Integer, Integer] | First and last page numbers where the receipt is found. Currently, only single-page receipts are supported. |
fields | Object | Dictionary of detected field values. |
type | String | Data type of the field value. Currently, possible types include "string", "number", "phoneNumber", "date", "time", "array", and "object". |
valueString | String | Semantic value of "string" fields. |
valueNumber | Number | Semantic value of "number" fields. |
valuePhoneNumber | String | Semantic value of "phoneNumber" fields. |
valueDate | String | Semantic value of "date" fields. |
valueTime | String | Semantic value of "time" fields. |
valueArray | [Object] | Semantic value of "array" fields. |
valueObject | Object | Semantic value of "object" fields. |
elements | [String] | When includeTextDetails is set to true, a list of references to the text elements constituting this field. |
Supported fields:
Name | Type | Example |
---|---|---|
ReceiptType | string | "Itemized" |
MerchantName | string | "Contoso" |
MerchantPhoneNumber | phoneNumber | "+19876543210" |
MerchantAddress | string | "123 Main St Redmond WA 98052" |
TransactionDate | date | "2019-06-26" |
TransactionTime | time | "16:49:00" |
Total | number | 14.34 |
Subtotal | number | 12.34 |
Tax | number | 2.00 |
Tip | number | 1.00 |
Items | array of objects |
[ { "Name": "Surface Pro 6", "Quantity": 1, "Price": 999.00, "TotalPrice": 999.00 }, { "Name": "SurfacePen", "Quantity": 2, "Price": 99.99, "TotalPrice": 199.98 } ] |
Name | string | "Surface Pro 6" |
Quantity | number | 1 |
Price | number | 999.00 |
TotalPrice | number | 999.00 |
{
"status": "succeeded",
"createdDateTime": "2020-05-13T07:29:49Z",
"lastUpdatedDateTime": "2020-05-13T07:29:57Z",
"analyzeResult": {
"version": "2.1.0",
"readResults": [
{
"page": 1,
"angle": 0.2816,
"width": 600,
"height": 1172,
"unit": "pixel"
}
],
"documentResults": [
{
"docType": "prebuilt:receipt",
"pageRange": [
1,
1
],
"fields": {
"ReceiptType": {
"type": "string",
"valueString": "Itemized",
"confidence": 0.878
},
"MerchantName": {
"type": "string",
"valueString": "Contoso",
"text": "Contoso",
"boundingBox": [
150.1,
97.9,
452.2,
120.4,
439.1,
296.5,
137,
274
],
"page": 1,
"confidence": 0.669
},
"MerchantAddress": {
"type": "string",
"valueString": "123 Main Street Redmond, WA 98052",
"text": "123 Main Street Redmond, WA 98052",
"boundingBox": [
132.8,
293,
321.8,
295.1,
321,
369.1,
132,
367
],
"page": 1,
"confidence": 0.994
},
"MerchantPhoneNumber": {
"type": "phoneNumber",
"text": "123-456-7890",
"boundingBox": [
129,
427,
263,
429,
262,
456,
128,
454
],
"page": 1,
"confidence": 0.995
},
"TransactionDate": {
"type": "date",
"valueDate": "2019-06-10",
"text": "6/10/2019",
"boundingBox": [
128,
520,
210,
521,
210,
551,
128,
550
],
"page": 1,
"confidence": 0.995
},
"TransactionTime": {
"type": "time",
"valueTime": "13:59:00",
"text": "13:59",
"boundingBox": [
216,
521,
269,
521,
269,
550,
216,
551
],
"page": 1,
"confidence": 0.995
},
"Items": {
"type": "array",
"valueArray": [
{
"type": "object",
"valueObject": {
"Quantity": {
"type": "number",
"valueNumber": 1,
"text": "1",
"boundingBox": [
140,
664,
149,
664,
149,
691,
140,
691
],
"page": 1,
"confidence": 0.922
},
"Name": {
"type": "string",
"valueString": "Surface Pro 6",
"text": "Surface Pro 6",
"boundingBox": [
154,
664,
289,
664,
289,
691,
154,
691
],
"page": 1,
"confidence": 0.956
},
"TotalPrice": {
"type": "number",
"valueNumber": 999,
"text": "$999.00",
"boundingBox": [
398,
762.7,
482,
764.5,
481.4,
791.8,
397.4,
790
],
"page": 1,
"confidence": 0.984
}
}
},
...
]
},
"Subtotal": {
"type": "number",
"valueNumber": 1098.99,
"text": "1098.99",
"boundingBox": [
407,
962,
483,
960,
484,
987,
408,
989
],
"page": 1,
"confidence": 0.987
},
"Total": {
"type": "number",
"valueNumber": 1203.39,
"text": "1203.39",
"boundingBox": [
404,
1105,
479,
1112,
476,
1139,
402,
1132
],
"page": 1,
"confidence": 0.959
},
"Tax": {
"type": "number",
"valueNumber": 104.4,
"text": "$104.40",
"boundingBox": [
415,
1010,
484,
1009,
483,
1036,
417,
1038
],
"page": 1,
"confidence": 0.615
}
}
}
]
}
}
Response 404
Invalid or expired result identifier.
{
"error": {
"code": "BadArgument",
"message": "Operation ID is invalid or expired."
}
}
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
}
}
Response 500
Internal server error.
{
"error": {
"code": "Unspecified",
"message": "Internal server error."
}
}
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
}
}
Response 503
Transient fault while querying Microsoft Azure storage services.
{
"error": {
"code": "StorageException",
"message": "Transient fault occurred while querying Microsoft Azure storage services. Please try again later."
}
}
{
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
}
}
Code samples
@ECHO OFF
curl -v -X GET "https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}"
-H "Ocp-Apim-Subscription-Key: {subscription key}"
--data-ascii "{body}"
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
namespace CSHttpClientSample
{
static class Program
{
static void Main()
{
MakeRequest();
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
static async void MakeRequest()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");
var uri = "https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}?" + queryString;
var response = await client.GetAsync(uri);
}
}
}
// // This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class JavaSample
{
public static void main(String[] args)
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "{subscription key}");
// Request body
StringEntity reqEntity = new StringEntity("{body}");
request.setEntity(reqEntity);
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null)
{
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString* path = @"https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}";
NSArray* array = @[
// Request parameters
@"entities=true",
];
NSString* string = [array componentsJoinedByString:@"&"];
path = [path stringByAppendingFormat:@"?%@", string];
NSLog(@"%@", path);
NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
[_request setHTTPMethod:@"GET"];
// Request headers
[_request setValue:@"{subscription key}" forHTTPHeaderField:@"Ocp-Apim-Subscription-Key"];
// Request body
[_request setHTTPBody:[@"{body}" dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
if (nil != error)
{
NSLog(@"Error: %@", error);
}
else
{
NSError* error = nil;
NSMutableDictionary* json = nil;
NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataString);
if (nil != _connectionData)
{
json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
}
if (error || !json)
{
NSLog(@"Could not parse loaded json with error:%@", error);
}
NSLog(@"%@", json);
_connectionData = nil;
}
[pool drain];
return 0;
}
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.urlencode({
})
try:
conn = httplib.HTTPSConnection('uaenorth.api.cognitive.microsoft.com')
conn.request("GET", "/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('uaenorth.api.cognitive.microsoft.com')
conn.request("GET", "/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
require 'net/http'
uri = URI('https://uaenorth.api.cognitive.microsoft.com/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}')
request = Net::HTTP::Get.new(uri.request_uri)
# Request headers
request['Ocp-Apim-Subscription-Key'] = '{subscription key}'
# Request body
request.body = "{body}"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body