UploadFile
UploadFile
Use this endpoint to upload a PDF, JPG, or PNG file to TaxBandits. The response gives you a FileId that you can pass to other endpoints, such as WhCertificate/Extract.
The file doesn't pass through the TaxBandits API. You upload it straight to secure storage (Amazon S3), where it's encrypted with your account's encryption key.
How It Works
- 1. Get an upload link — Call
Utility/UploadFilewith the type of the file you'll upload. The response returns aFileId, aPreSignedUrl, andPreSignedFields. - 2. Upload the file to S3 — Before
ExpiresAt, send the file to thePreSignedUrlwith thePreSignedFieldsand your encryption fields. See Upload the File to S3. - 3. Use the FileId — After the upload succeeds, pass the
FileIdto an endpoint that accepts it, such as WhCertificate/Extract.
| Requirement | Value |
|---|---|
| Supported formats | PDF, JPG, PNG |
| Maximum file size | 5 MB |
| Upload link expiry | 1 minute after it's created |
| Encryption | AES-256, with your account's encryption key |
POST Utility/UploadFile Request Headers
| Header | Value |
|---|---|
| Authorization | <AccessToken> |
| Content-Type | application/json |
Request Body
| Field | Type | Description |
|---|---|---|
| ContentType | String | Type of the file you'll upload.Allowed values"application/pdf", "image/jpeg", "image/png" |
Response Body
| Field | Type | Description |
|---|---|---|
| FileId | GUID | Unique ID of the file. After the upload is complete, pass it to an endpoint that accepts a FileId, such as WhCertificate/Extract . |
| PreSignedUrl | String | S3 address to send the file to. |
| PreSignedFields | Object | Form fields to send, unchanged, with the file to S3. |
| key | String | Storage path of the file. Format: <Filepath>.<ext> (ext is pdf, jpg, or png) |
| policy | String | Base64-encoded upload rules: expiry, file type, size limit, and encryption. |
| X-Amz-Algorithm | String | Signing algorithm. Always AWS4-HMAC-SHA256. |
| X-Amz-Credential | String | Credential scope used to sign the upload. |
| X-Amz-Date | String | Date and time (UTC) the upload was signed. |
| X-Amz-Signature | String | Signature that protects the upload fields from changes. |
| Content-Type | String | File type. Same as the ContentType in the request. |
| ExpiresAt | String | Date and time the upload link expires. Format: YYYY-MM-DD HH:MM:SS ±HH:MM |
| Errors | Object [] | Detailed error information. |
| Id | String | Validation error ID. |
| Name | String | Name of the validation error. |
| Message | String | Description of the validation error. |
Upload the File to S3
Send a POST request to the PreSignedUrl with a multipart/form-data body that has the fields below. Don't send the Authorization header to S3.
S3 Form Fields
| Field | Type | Description |
|---|---|---|
All PreSignedFields entries | String | Each name and value exactly as returned: key, policy, X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Signature, and Content-Type. |
| x-amz-server-side-encryption-customer-algorithm | String | Encryption algorithm. Always AES256. |
| x-amz-server-side-encryption-customer-key | String | Your account's encryption key: a 256-bit key, Base64-encoded. |
| x-amz-server-side-encryption-customer-key-MD5 | String | MD5 hash of your encryption key, Base64-encoded. See Calculate the Key MD5. |
| file | File | The file to upload. Must be the last field. |
- Send the
PreSignedFieldsexactly as you received them. Don't rename or change any of them. - Put the
filefield last. S3 ignores any field sent after it. - Complete the upload before
ExpiresAt. If the link expires, callUtility/UploadFileagain to get a new one. - Use the
FileIdonly after S3 confirms the upload.
Calculate the Key MD5
The x-amz-server-side-encryption-customer-key-MD5 field is the MD5 hash of your encryption key. Decode the key from Base64 first, hash the decoded bytes, then Base64-encode the hash.
- Bash
- NodeJs
- C#
- Python
- Java
- Go
- PHP
- Ruby
echo -n '<<Encryption Key>>' | base64 -d | openssl md5 -binary | base64
const crypto = require("crypto");
const encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
// MD5 of the decoded key bytes, Base64-encoded
const keyMD5 = crypto.createHash("md5").update(Buffer.from(encryptionKey, "base64")).digest("base64");
console.log(keyMD5);
using System;
using System.Security.Cryptography;
var encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
// MD5 of the decoded key bytes, Base64-encoded
var keyMD5 = Convert.ToBase64String(MD5.HashData(Convert.FromBase64String(encryptionKey)));
Console.WriteLine(keyMD5);
import base64
import hashlib
encryption_key = "<<Encryption Key>>" # Your account's encryption key (Base64)
# MD5 of the decoded key bytes, Base64-encoded
key_md5 = base64.b64encode(hashlib.md5(base64.b64decode(encryption_key)).digest()).decode()
print(key_md5)
import java.security.MessageDigest;
import java.util.Base64;
public class GenerateKeyMD5 {
public static void main(String[] args) throws Exception {
String encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
// MD5 of the decoded key bytes, Base64-encoded
byte[] key = Base64.getDecoder().decode(encryptionKey);
String keyMD5 = Base64.getEncoder().encodeToString(MessageDigest.getInstance("MD5").digest(key));
System.out.println(keyMD5);
}
}
package main
import (
"crypto/md5"
"encoding/base64"
"fmt"
)
func main() {
encryptionKey := "<<Encryption Key>>" // Your account's encryption key (Base64)
// MD5 of the decoded key bytes, Base64-encoded
key, err := base64.StdEncoding.DecodeString(encryptionKey)
if err != nil {
panic(err)
}
sum := md5.Sum(key)
fmt.Println(base64.StdEncoding.EncodeToString(sum[:]))
}
<?php
$encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
// MD5 of the decoded key bytes, Base64-encoded
$keyMD5 = base64_encode(md5(base64_decode($encryptionKey), true));
echo $keyMD5 . PHP_EOL;
require "digest"
encryption_key = "<<Encryption Key>>" # Your account's encryption key (Base64)
# MD5 of the decoded key bytes, Base64-encoded ("m0" = strict Base64 decode)
key_md5 = Digest::MD5.base64digest(encryption_key.unpack1("m0"))
puts key_md5
Check your code: run it with the sample key below and compare the result. This key is only for testing.
| Value | Sample |
|---|---|
| Encryption key | MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY= |
| Expected key MD5 | hRasmdxgYDKV3nvbahU1MA== |
If you get t52DDCIm7WL8PC2PMFZOiw==, you hashed the Base64 text instead of the decoded key bytes.
Sample Code
Each sample does all three steps: it gets the upload link from Utility/UploadFile, calculates the key MD5, and posts the file to S3. Replace the values in <<...>> with your own. In the cURL sample, copy the PreSignedUrl and PreSignedFields values from the step 1 response into step 3.
- cURL
- NodeJs
- C#
- Python
- Java
- Go
- PHP
- Ruby
# Step 1: Get the upload link
curl --location '<<TaxBandits API URL>>/v2.0.0/Utility/UploadFile' \
--header 'Authorization: <<Access Token>>' \
--header 'Content-Type: application/json' \
--data '{ "ContentType": "application/pdf" }'
# Step 2: Calculate the key MD5
ENCRYPTION_KEY='<<Encryption Key>>'
KEY_MD5=$(echo -n "$ENCRYPTION_KEY" | base64 -d | openssl md5 -binary | base64)
# Step 3: Post the file to S3. Copy PreSignedUrl and each PreSignedFields value from the step 1 response.
curl --location '<<PreSignedUrl>>' \
--form-string 'Content-Type=application/pdf' \
--form-string 'X-Amz-Algorithm=AWS4-HMAC-SHA256' \
--form-string 'X-Amz-Credential=<<X-Amz-Credential>>' \
--form-string 'X-Amz-Date=<<X-Amz-Date>>' \
--form-string 'X-Amz-Signature=<<X-Amz-Signature>>' \
--form-string 'key=<<key>>' \
--form-string 'policy=<<policy>>' \
--form-string 'x-amz-server-side-encryption-customer-algorithm=AES256' \
--form-string "x-amz-server-side-encryption-customer-key=$ENCRYPTION_KEY" \
--form-string "x-amz-server-side-encryption-customer-key-MD5=$KEY_MD5" \
--form 'file=@"<<File Path>>";type=application/pdf' \
--write-out 'S3 status: %{http_code}\n'
// Node.js 18 or later (uses the built-in fetch, FormData and Blob)
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
// Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
const generateKeyMD5 = (encryptionKey) =>
crypto.createHash("md5").update(Buffer.from(encryptionKey, "base64")).digest("base64");
const uploadFile = async (apiUrl, accessToken, encryptionKey, filePath, contentType) => {
// Step 1: Get the upload link
const linkResponse = await fetch(apiUrl + "/v2.0.0/Utility/UploadFile", {
method: "POST",
headers: { "Authorization": accessToken, "Content-Type": "application/json" },
body: JSON.stringify({ ContentType: contentType })
});
const upload = await linkResponse.json();
if (linkResponse.status !== 200) {
console.log("Error in UploadFile:", linkResponse.status, JSON.stringify(upload.Errors));
return;
}
// Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
const form = new FormData();
for (const [name, value] of Object.entries(upload.PreSignedFields)) {
form.append(name, value);
}
form.append("x-amz-server-side-encryption-customer-algorithm", "AES256");
form.append("x-amz-server-side-encryption-customer-key", encryptionKey);
form.append("x-amz-server-side-encryption-customer-key-MD5", generateKeyMD5(encryptionKey));
form.append("file", new Blob([fs.readFileSync(filePath)], { type: contentType }), path.basename(filePath));
// Step 3: Post the form to S3 (without the Authorization header)
const s3Response = await fetch(upload.PreSignedUrl, { method: "POST", body: form });
if (s3Response.status === 204) {
console.log("Upload complete. FileId:", upload.FileId);
} else {
console.log("Upload failed:", s3Response.status, await s3Response.text());
}
};
const apiUrl = "<<TaxBandits API URL>>"; // API base URL, without the version
const accessToken = "<<Access Token>>"; // JWT access token from the OAuth server
const encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
const filePath = "<<File Path>>"; // File to upload, e.g. W9.pdf
const contentType = "application/pdf"; // application/pdf, image/jpeg or image/png
uploadFile(apiUrl, accessToken, encryptionKey, filePath, contentType);
// .NET 6 or later
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
class UploadFileSample
{
static readonly HttpClient client = new HttpClient();
// Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
static string GenerateKeyMD5(string encryptionKey) =>
Convert.ToBase64String(MD5.HashData(Convert.FromBase64String(encryptionKey)));
// Adds a form field the way a browser does: quoted name, no Content-Type header
static void AddField(MultipartFormDataContent form, string name, string value)
{
var field = new StringContent(value);
field.Headers.ContentType = null;
field.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = '"' + name + '"' };
form.Add(field);
}
static async Task UploadFile(string apiUrl, string accessToken, string encryptionKey, string filePath, string contentType)
{
// Step 1: Get the upload link
var request = new HttpRequestMessage(HttpMethod.Post, apiUrl + "/v2.0.0/Utility/UploadFile");
request.Headers.TryAddWithoutValidation("Authorization", accessToken);
request.Content = new StringContent(JsonSerializer.Serialize(new { ContentType = contentType }), Encoding.UTF8, "application/json");
var linkResponse = await client.SendAsync(request);
var upload = JsonDocument.Parse(await linkResponse.Content.ReadAsStringAsync()).RootElement;
if (linkResponse.StatusCode != HttpStatusCode.OK)
{
var errors = upload.TryGetProperty("Errors", out var e) ? e.ToString() : "";
Console.WriteLine("Error in UploadFile: " + (int)linkResponse.StatusCode + " " + errors);
return;
}
// Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
var form = new MultipartFormDataContent();
foreach (var field in upload.GetProperty("PreSignedFields").EnumerateObject())
{
AddField(form, field.Name, field.Value.GetString());
}
AddField(form, "x-amz-server-side-encryption-customer-algorithm", "AES256");
AddField(form, "x-amz-server-side-encryption-customer-key", encryptionKey);
AddField(form, "x-amz-server-side-encryption-customer-key-MD5", GenerateKeyMD5(encryptionKey));
var file = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
file.Headers.ContentType = new MediaTypeHeaderValue(contentType);
file.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"file\"",
FileName = '"' + Path.GetFileName(filePath) + '"'
};
form.Add(file);
// Step 3: Post the form to S3 (without the Authorization header)
var s3Response = await client.PostAsync(upload.GetProperty("PreSignedUrl").GetString(), form);
if (s3Response.StatusCode == HttpStatusCode.NoContent)
{
Console.WriteLine("Upload complete. FileId: " + upload.GetProperty("FileId").GetString());
}
else
{
Console.WriteLine("Upload failed: " + (int)s3Response.StatusCode + " " + await s3Response.Content.ReadAsStringAsync());
}
}
static async Task Main()
{
var apiUrl = "<<TaxBandits API URL>>"; // API base URL, without the version
var accessToken = "<<Access Token>>"; // JWT access token from the OAuth server
var encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
var filePath = "<<File Path>>"; // File to upload, e.g. W9.pdf
var contentType = "application/pdf"; // application/pdf, image/jpeg or image/png
await UploadFile(apiUrl, accessToken, encryptionKey, filePath, contentType);
}
}
# Python 3 with the requests package (pip install requests)
import base64
import hashlib
import os
import requests
def generate_key_md5(encryption_key):
# Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
return base64.b64encode(hashlib.md5(base64.b64decode(encryption_key)).digest()).decode()
def upload_file(api_url, access_token, encryption_key, file_path, content_type):
# Step 1: Get the upload link
link_response = requests.post(
api_url + "/v2.0.0/Utility/UploadFile",
headers={"Authorization": access_token, "Content-Type": "application/json"},
json={"ContentType": content_type},
)
upload = link_response.json()
if link_response.status_code != 200:
print("Error in UploadFile:", link_response.status_code, upload.get("Errors"))
return
# Step 2: Build the form - PreSignedFields, then the encryption fields (requests sends the file last)
fields = dict(upload["PreSignedFields"])
fields["x-amz-server-side-encryption-customer-algorithm"] = "AES256"
fields["x-amz-server-side-encryption-customer-key"] = encryption_key
fields["x-amz-server-side-encryption-customer-key-MD5"] = generate_key_md5(encryption_key)
# Step 3: Post the form to S3 (without the Authorization header)
with open(file_path, "rb") as file:
s3_response = requests.post(
upload["PreSignedUrl"],
data=fields,
files={"file": (os.path.basename(file_path), file, content_type)},
)
if s3_response.status_code == 204:
print("Upload complete. FileId:", upload["FileId"])
else:
print("Upload failed:", s3_response.status_code, s3_response.text)
api_url = "<<TaxBandits API URL>>" # API base URL, without the version
access_token = "<<Access Token>>" # JWT access token from the OAuth server
encryption_key = "<<Encryption Key>>" # Your account's encryption key (Base64)
file_path = "<<File Path>>" # File to upload, e.g. W9.pdf
content_type = "application/pdf" # application/pdf, image/jpeg or image/png
upload_file(api_url, access_token, encryption_key, file_path, content_type)
// Java 11 or later, with Gson (com.google.code.gson:gson) for JSON
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;
public class UploadFileSample {
static final HttpClient client = HttpClient.newHttpClient();
public static void main(String[] args) throws Exception {
String apiUrl = "<<TaxBandits API URL>>"; // API base URL, without the version
String accessToken = "<<Access Token>>"; // JWT access token from the OAuth server
String encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
String filePath = "<<File Path>>"; // File to upload, e.g. W9.pdf
String contentType = "application/pdf"; // application/pdf, image/jpeg or image/png
uploadFile(apiUrl, accessToken, encryptionKey, filePath, contentType);
}
// Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
static String generateKeyMD5(String encryptionKey) throws Exception {
byte[] key = Base64.getDecoder().decode(encryptionKey);
return Base64.getEncoder().encodeToString(MessageDigest.getInstance("MD5").digest(key));
}
static void uploadFile(String apiUrl, String accessToken, String encryptionKey, String filePath, String contentType) throws Exception {
// Step 1: Get the upload link
JsonObject body = new JsonObject();
body.addProperty("ContentType", contentType);
HttpRequest linkRequest = HttpRequest.newBuilder(URI.create(apiUrl + "/v2.0.0/Utility/UploadFile"))
.header("Authorization", accessToken)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body.toString()))
.build();
HttpResponse<String> linkResponse = client.send(linkRequest, HttpResponse.BodyHandlers.ofString());
JsonObject upload = JsonParser.parseString(linkResponse.body()).getAsJsonObject();
if (linkResponse.statusCode() != 200) {
System.out.println("Error in UploadFile: " + linkResponse.statusCode() + " " + upload.get("Errors"));
return;
}
// Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
String boundary = UUID.randomUUID().toString();
ByteArrayOutputStream form = new ByteArrayOutputStream();
for (Map.Entry<String, JsonElement> field : upload.getAsJsonObject("PreSignedFields").entrySet()) {
addField(form, boundary, field.getKey(), field.getValue().getAsString());
}
addField(form, boundary, "x-amz-server-side-encryption-customer-algorithm", "AES256");
addField(form, boundary, "x-amz-server-side-encryption-customer-key", encryptionKey);
addField(form, boundary, "x-amz-server-side-encryption-customer-key-MD5", generateKeyMD5(encryptionKey));
Path file = Path.of(filePath);
write(form, "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getFileName() + "\"\r\n"
+ "Content-Type: " + contentType + "\r\n\r\n");
form.write(Files.readAllBytes(file));
write(form, "\r\n--" + boundary + "--\r\n");
// Step 3: Post the form to S3 (without the Authorization header)
HttpRequest s3Request = HttpRequest.newBuilder(URI.create(upload.get("PreSignedUrl").getAsString()))
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofByteArray(form.toByteArray()))
.build();
HttpResponse<String> s3Response = client.send(s3Request, HttpResponse.BodyHandlers.ofString());
if (s3Response.statusCode() == 204) {
System.out.println("Upload complete. FileId: " + upload.get("FileId").getAsString());
} else {
System.out.println("Upload failed: " + s3Response.statusCode() + " " + s3Response.body());
}
}
static void addField(ByteArrayOutputStream form, String boundary, String name, String value) throws Exception {
write(form, "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n"
+ value + "\r\n");
}
static void write(ByteArrayOutputStream form, String text) throws Exception {
form.write(text.getBytes(StandardCharsets.UTF_8));
}
}
package main
import (
"bytes"
"crypto/md5"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"path/filepath"
)
type uploadFileResponse struct {
FileId string `json:"FileId"`
PreSignedUrl string `json:"PreSignedUrl"`
PreSignedFields map[string]string `json:"PreSignedFields"`
ExpiresAt string `json:"ExpiresAt"`
Errors json.RawMessage `json:"Errors"`
}
// generateKeyMD5 returns the Base64 MD5 of the decoded key bytes (not of the Base64 text).
func generateKeyMD5(encryptionKey string) (string, error) {
key, err := base64.StdEncoding.DecodeString(encryptionKey)
if err != nil {
return "", err
}
sum := md5.Sum(key)
return base64.StdEncoding.EncodeToString(sum[:]), nil
}
func uploadFile(apiURL, accessToken, encryptionKey, filePath, contentType string) error {
// Step 1: Get the upload link
body, _ := json.Marshal(map[string]string{"ContentType": contentType})
req, err := http.NewRequest("POST", apiURL+"/v2.0.0/Utility/UploadFile", bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Authorization", accessToken)
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
var upload uploadFileResponse
if err := json.NewDecoder(res.Body).Decode(&upload); err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("error in UploadFile: %d %s", res.StatusCode, upload.Errors)
}
keyMD5, err := generateKeyMD5(encryptionKey)
if err != nil {
return err
}
fileBytes, err := os.ReadFile(filePath)
if err != nil {
return err
}
// Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
var form bytes.Buffer
writer := multipart.NewWriter(&form)
for name, value := range upload.PreSignedFields {
writer.WriteField(name, value)
}
writer.WriteField("x-amz-server-side-encryption-customer-algorithm", "AES256")
writer.WriteField("x-amz-server-side-encryption-customer-key", encryptionKey)
writer.WriteField("x-amz-server-side-encryption-customer-key-MD5", keyMD5)
fileHeader := make(textproto.MIMEHeader)
fileHeader.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filepath.Base(filePath)))
fileHeader.Set("Content-Type", contentType)
filePart, err := writer.CreatePart(fileHeader)
if err != nil {
return err
}
filePart.Write(fileBytes)
writer.Close()
// Step 3: Post the form to S3 (without the Authorization header)
s3Res, err := http.Post(upload.PreSignedUrl, writer.FormDataContentType(), &form)
if err != nil {
return err
}
defer s3Res.Body.Close()
if s3Res.StatusCode != http.StatusNoContent {
msg, _ := io.ReadAll(s3Res.Body)
return fmt.Errorf("upload failed: %d %s", s3Res.StatusCode, msg)
}
fmt.Println("Upload complete. FileId:", upload.FileId)
return nil
}
func main() {
apiURL := "<<TaxBandits API URL>>" // API base URL, without the version
accessToken := "<<Access Token>>" // JWT access token from the OAuth server
encryptionKey := "<<Encryption Key>>" // Your account's encryption key (Base64)
filePath := "<<File Path>>" // File to upload, e.g. W9.pdf
contentType := "application/pdf" // application/pdf, image/jpeg or image/png
if err := uploadFile(apiURL, accessToken, encryptionKey, filePath, contentType); err != nil {
fmt.Println(err)
}
}
<?php
// PHP 7.4 or later, with the curl extension
// Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
function generateKeyMD5($encryptionKey)
{
return base64_encode(md5(base64_decode($encryptionKey), true));
}
function uploadFile($apiUrl, $accessToken, $encryptionKey, $filePath, $contentType)
{
// Step 1: Get the upload link
$ch = curl_init($apiUrl . "/v2.0.0/Utility/UploadFile");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: " . $accessToken, "Content-Type: application/json"],
CURLOPT_POSTFIELDS => json_encode(["ContentType" => $contentType]),
]);
$upload = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status != 200) {
echo "Error in UploadFile: " . $status . " " . json_encode($upload["Errors"] ?? null) . PHP_EOL;
return;
}
// Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
$form = $upload["PreSignedFields"];
$form["x-amz-server-side-encryption-customer-algorithm"] = "AES256";
$form["x-amz-server-side-encryption-customer-key"] = $encryptionKey;
$form["x-amz-server-side-encryption-customer-key-MD5"] = generateKeyMD5($encryptionKey);
$form["file"] = new CURLFile($filePath, $contentType, basename($filePath));
// Step 3: Post the form to S3 (without the Authorization header)
$ch = curl_init($upload["PreSignedUrl"]);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $form,
]);
$s3Body = curl_exec($ch);
$s3Status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($s3Status == 204) {
echo "Upload complete. FileId: " . $upload["FileId"] . PHP_EOL;
} else {
echo "Upload failed: " . $s3Status . " " . $s3Body . PHP_EOL;
}
}
$apiUrl = "<<TaxBandits API URL>>"; // API base URL, without the version
$accessToken = "<<Access Token>>"; // JWT access token from the OAuth server
$encryptionKey = "<<Encryption Key>>"; // Your account's encryption key (Base64)
$filePath = "<<File Path>>"; // File to upload, e.g. W9.pdf
$contentType = "application/pdf"; // application/pdf, image/jpeg or image/png
uploadFile($apiUrl, $accessToken, $encryptionKey, $filePath, $contentType);
# Ruby 2.7 or later (standard library only)
require "net/http"
require "uri"
require "json"
require "digest"
# Returns the Base64 MD5 of the decoded key bytes (not of the Base64 text)
def generate_key_md5(encryption_key)
Digest::MD5.base64digest(encryption_key.unpack1("m0")) # "m0" = strict Base64 decode
end
def upload_file(api_url, access_token, encryption_key, file_path, content_type)
# Step 1: Get the upload link
uri = URI(api_url + "/v2.0.0/Utility/UploadFile")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = access_token
request["Content-Type"] = "application/json"
request.body = JSON.dump({ "ContentType" => content_type })
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(request) }
upload = JSON.parse(response.body)
unless response.code == "200"
puts "Error in UploadFile: #{response.code} #{upload["Errors"]}"
return
end
# Step 2: Build the form - PreSignedFields, then the encryption fields, then the file (last)
form = upload["PreSignedFields"].to_a
form << ["x-amz-server-side-encryption-customer-algorithm", "AES256"]
form << ["x-amz-server-side-encryption-customer-key", encryption_key]
form << ["x-amz-server-side-encryption-customer-key-MD5", generate_key_md5(encryption_key)]
form << ["file", File.open(file_path, "rb"), { filename: File.basename(file_path), content_type: content_type }]
# Step 3: Post the form to S3 (without the Authorization header)
s3_uri = URI(upload["PreSignedUrl"])
s3_request = Net::HTTP::Post.new(s3_uri)
s3_request.set_form(form, "multipart/form-data")
s3_response = Net::HTTP.start(s3_uri.host, s3_uri.port, use_ssl: s3_uri.scheme == "https") { |http| http.request(s3_request) }
if s3_response.code == "204"
puts "Upload complete. FileId: #{upload["FileId"]}"
else
puts "Upload failed: #{s3_response.code} #{s3_response.body}"
end
end
api_url = "<<TaxBandits API URL>>" # API base URL, without the version
access_token = "<<Access Token>>" # JWT access token from the OAuth server
encryption_key = "<<Encryption Key>>" # Your account's encryption key (Base64)
file_path = "<<File Path>>" # File to upload, e.g. W9.pdf
content_type = "application/pdf" # application/pdf, image/jpeg or image/png
upload_file(api_url, access_token, encryption_key, file_path, content_type)
Common Errors
Utility/UploadFile
| Status / Error | Description |
|---|---|
| 400 – C00-000409 | ContentType is missing, or isn't application/pdf, image/jpeg, or image/png. |
| 401 – Unauthorized | The access token is missing, invalid, or expired. |
S3 Upload
| Status / Error | Description |
|---|---|
| 403 – Policy expired | The upload link expired. Call Utility/UploadFile again. |
| 400 – EntityTooLarge | The file is larger than 5 MB. |
| 400 – EntityTooSmall | The file is empty. |
| 403 – Invalid according to Policy | A field is missing or changed, Content-Type differs from the returned value, or the encryption key or its MD5 is wrong. |
| 400 – InvalidArgument | The encryption key isn't a valid 256-bit Base64 key, or doesn't match the key MD5 you sent. |
Payload

Go Lang
Node.js
Python
.NET C#

Ruby
Java

cURL
| Sample | Description | Action |
|---|---|---|
| Sample 1 | Requests a pre-signed URL to upload a PDF file. |
Sample 1
{
"ContentType": "application/pdf"
}
| Sample | Description | Action |
|---|---|---|
| 200 | Success Response - This is a sample response for successful API requests. | |
| 401 | Unauthorized Response - You'll get the below response when your API requests don't contain valid authentication credentials. |
Response: 200
{
"FileId": "3f1c2a9e-7b4d-4c1a-9e2f-1a2b3c4d5e6f",
"PreSignedUrl": "https://<bucket>.s3.us-east-1.amazonaws.com",
"PreSignedFields": {
"Content-Type": "application/pdf",
"X-Amz-Algorithm": "AWS4-HMAC-SHA256",
"X-Amz-Credential": "<Credential>",
"X-Amz-Date": "<Date>",
"X-Amz-Signature": "<Signature>",
"key": "<FileName>",
"policy": "<Base64Policy>"
},
"ExpiresAt": "2026-07-07 10:25:31 -04:00",
"Errors": null
}
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
url := "<APIURL>/v2.0.0/Utility/UploadFile"
method := "POST"
payload := strings.NewReader(`{
"ContentType": "application/pdf"
}`)
client := &http.Client{}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Authorization", "<ACCESS_TOKEN>")
req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Status:", res.Status)
fmt.Println(string(body))
}
const axios = require('axios');
let data = JSON.stringify({
"ContentType": "application/pdf"
});
let config = {
method: 'post',
maxBodyLength: Infinity,
url: '<APIURL>/v2.0.0/Utility/UploadFile',
headers: {
'Authorization': '<ACCESS_TOKEN>',
'Content-Type': 'application/json'
},
data : data
};
axios.request(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
import http.client
import json
conn = http.client.HTTPSConnection("<APIURL>")
payload = json.dumps({
"ContentType": "application/pdf"
})
headers = {
'Authorization': '<ACCESS_TOKEN>',
'Content-Type': 'application/json'
}
conn.request("POST", "/v2.0.0/Utility/UploadFile", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "<APIURL>/v2.0.0/Utility/UploadFile");
request.Headers.Add("Authorization", "<ACCESS_TOKEN>");
var content = new StringContent("{\r\n\t\"ContentType\": \"application/pdf\"\r\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
require "uri"
require "json"
require "net/http"
url = URI("<APIURL>/v2.0.0/Utility/UploadFile")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = "<ACCESS_TOKEN>"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
"ContentType": "application/pdf"
})
response = https.request(request)
puts response.read_body
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\r\n\t\"ContentType\": \"application/pdf\"\r\n}");
Request request = new Request.Builder()
.url("<APIURL>/v2.0.0/Utility/UploadFile")
.method("POST", body)
.addHeader("Authorization", "<ACCESS_TOKEN>")
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
curl --location '<APIURL>/v2.0.0/Utility/UploadFile' \
--header 'Authorization: <ACCESS_TOKEN>' \
--header 'Content-Type: application/json' \
--data '{
"ContentType": "application/pdf"
}'