Integration Quickstart

Overview

Generating documents via the Lawyered API requires sending a strictly typed JSON payload and correctly handling the resulting binary file stream.

Choose your preferred backend language below for a complete, production-ready example demonstrating how to generate a Non-Disclosure Agreement (NDA) and save the resulting PDF directly to your local file system.

The document generation endpoint is `https://api.lawyeredapp.com/api/v1/documents/generate`. Note the `/api` prefix — requests without it will not reach the API.

TypeScript (Node.js)

Prerequisites:

  • Node.js installed (v18+ recommended for native fetch support).
  • Your API key stored as an environment variable (LAWYERED_API_KEY).
import fs from 'fs/promises';

/**
 * Quickstart: Generate a Non-Disclosure Agreement
 */
async function generateAgreement() {
  const apiKey = process.env.LAWYERED_API_KEY;

  if (!apiKey) {
    console.error("Missing LAWYERED_API_KEY environment variable.");
    return;
  }

  // 1. Construct the payload matching the template schema.
  //    Note: `parties` is a required array — agreement templates will fail
  //    to generate if required arrays are missing or empty.
  const payload = {
    templateId: "non-disclosure-agreement",
    format: "pdf",
    data: {
      project: "System Architecture Review",
      ndaDuration: "24 months",
      governingLaw: "Nigeria",
      parties: [
        {
          isCompany: true,
          rcName: "Acme Corp",
          rcCountry: "United States",
          rcNumber: "12345678",
          type: "Private Company limited by shares"
        },
        {
          isCompany: false,
          fullName: "Joshua",
          address: "789 Alpha Ave",
          rcCountry: "Nigeria"
        }
      ]
    }
  };

  try {
    console.log("Generating document...");

    // 2. Call the Document Generation endpoint
    const response = await fetch('https://api.lawyeredapp.com/api/v1/documents/generate', {
      method: 'POST',
      headers: {
        'X-Key': apiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      // Error responses are JSON. See "Error responses" below for the shapes.
      const errorData = await response.json();
      throw new Error(`API Error ${response.status}: ${JSON.stringify(errorData, null, 2)}`);
    }

    // 3. Handle the binary response and save to disk
    const arrayBuffer = await response.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    const fileName = `./Acme_NDA_${Date.now()}.pdf`;
    await fs.writeFile(fileName, buffer);

    console.log(`Success! Document saved as ${fileName}`);

  } catch (error) {
    console.error('Failed to generate document:\n', error);
  }
}

generateAgreement();

Python

Prerequisites:

  • Python 3.7+ installed.
  • The requests library installed (pip install requests).
  • Your API key stored as an environment variable (LAWYERED_API_KEY).
import os
import requests

def generate_agreement():
    api_key = os.getenv("LAWYERED_API_KEY")
    if not api_key:
        print("Error: Missing LAWYERED_API_KEY environment variable.")
        return

    url = "https://api.lawyeredapp.com/api/v1/documents/generate"

    headers = {
        "X-Key": api_key,
        "Content-Type": "application/json"
    }

    # 1. Construct the payload matching the template schema.
    #    Note: `parties` is a required array — agreement templates will fail
    #    to generate if required arrays are missing or empty.
    payload = {
        "templateId": "non-disclosure-agreement",
        "format": "pdf",
        "data": {
            "project": "System Architecture Review",
            "ndaDuration": "24 months",
            "governingLaw": "Nigeria",
            "parties": [
                {
                    "isCompany": True,
                    "rcName": "Acme Corp",
                    "rcCountry": "United States",
                    "rcNumber": "12345678",
                    "type": "Private Company limited by shares"
                },
                {
                    "isCompany": False,
                    "fullName": "Joshua",
                    "address": "789 Alpha Ave",
                    "rcCountry": "Nigeria"
                }
            ]
        }
    }

    try:
        print("Generating document...")

        # 2. Call the Document Generation endpoint
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()

        # 3. Handle the binary response and save to disk
        file_name = "Acme_NDA_Generated.pdf"
        with open(file_name, "wb") as f:
            f.write(response.content)

        print(f"Success! Document saved as {file_name}")

    except requests.exceptions.HTTPError as err:
        print(f"API Error: {err}")
        print(response.json())
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    generate_agreement()

Providing template data

Each template defines its own required fields in its Template Schema. Two behaviours are worth designing around:

  • Policy templates (e.g. ESG, environmental, labour and other policies) are tolerant of sparse data and will generate even when optional fields are omitted.
  • Agreement templates (e.g. the NDA and Supplier Agreement) contain required arrays such as parties. If a required array is missing or empty, generation will fail — a contract cannot be rendered without its parties. Always collect and pass the required array fields before calling the endpoint.

When in doubt, consult the template's schema for which fields are required and which are conditional.


Error responses

Errors are returned as JSON. The shape depends on where the request fails:

StatusMeaningBody
401Missing X-Key header{ "error": "Unauthorized: Missing X-Key header" }
403Invalid or revoked API key{ "error": "Forbidden: Invalid or revoked API Key" }
500Template not found, or generation failed (e.g. a required array was empty){ "status": "error", "message": "..." }
A successful call returns raw binary data (`application/pdf` or the `.docx` bytes), **not** JSON. Only error responses are JSON, so check the response status before attempting to parse the body as JSON.

Key Takeaways

When building this into your backend architecture, keep the following concepts in mind:

  1. Endpoint: Use https://api.lawyeredapp.com/api/v1/documents/generate, including the /api prefix.
  2. Authentication: Always pass your API key via the X-Key header. Never expose this key in client-side code or public repositories.
  3. Required fields: The data object should match the rules defined in the template's schema. Agreement templates require their array fields (such as parties) to be present and non-empty.
  4. Binary Handling: A successful response is raw binary data (application/pdf or .docx), not JSON. Depending on your environment, extract the response as an ArrayBuffer or raw byte stream before writing it to your file system or routing it to a cloud storage bucket.