Skip to content

Python Client

The Werk24 Python client enables seamless extraction of structured data from technical drawings. This section demonstrates different implementation approaches: synchronous processing, asynchronous processing, and callback-based integration.

You need an API key for any of these: see Get an API key.

Working in another language?

You do not need Python. Any language that can send a form upload and receive a webhook can read a drawing: see HTTP API (any language) for curl, C# and Java.

Choose the Right Approach

Use the table below to determine which implementation best suits your use case. Each implementation covers most use cases, but some suit your use case better than others, and the callback approach only takes drawings up to about 4.6 MB.

Use Case Synchronous Asynchronous Callback
Quick, one-time extraction ✅ Recommended ~ ~
Processing multiple drawings concurrently from local machine ~ ✅ Recommended ~
Integration with web applications or APIs ~ ~ ✅ Recommended
Drawings between about 4.6 MB and 10 MiB ✅ ✅ ❌ Not possible

Synchronous Implementation

If you need a quick way to extract metadata from a technical drawing, the synchronous approach is the easiest method:

from werk24 import read_drawing_sync, get_test_drawing, AskMetaData

# Load a sample drawing for testing
test_drawing = get_test_drawing()

# Extract metadata from the drawing
results = read_drawing_sync(test_drawing, [AskMetaData()])

# Print extracted metadata
print(results)

Explanation

  • get_test_drawing() provides a sample drawing to test the function.
  • read_drawing_sync() sends the drawing to Werk24 and retrieves structured metadata.
  • The response is printed as a list of TechreadMessages, ready for further processing.

Limitation

This method blocks execution until the request is complete. It is not suitable for processing multiple drawings concurrently or integrating with asynchronous systems.

Asynchronous Implementation

For more complex applications, you can use an asynchronous approach to handle requests efficiently, allowing the system to process multiple drawings simultaneously.

import asyncio
from werk24 import (
    Werk24Client, AskMetaData, TechreadMessage, Hook, get_test_drawing
)


def recv(message:TechreadMessage):
    """
    Handles the response from Werk24 when a drawing is processed.

    Args:
    ----
    - message (TechreadMessage): The response message from the Werk24 server. 
      This message corresponds to the specific `Ask` request in the Hook.
    """
    if message.is_successful:
        print(f"Successfully processed the drawing:")
        print(message.payload_dict)
    else:
        print(f"Failed to process the drawing:")
        print(message.exceptions)

async def read_drawing(path: str):
    """
    Sends a technical drawing to Werk24 for analysis.

    Args:
    ----
    - path (str): Path of the file to process.
    """

    # Specify which information you want to obtain, and
    # which function shall be called when the information
    # is available.
    hooks = [Hook(ask=AskMetaData(), function=recv)]

    # Open the file and send it for processing
    with open(path, "rb") as fid:
        async with Werk24Client() as client:
            await client.read_drawing_with_hooks(fid, hooks)

# Run the asynchronous function
asyncio.run(read_drawing("<path>"))

Explanation

  • Asynchronous processing: asyncio.run() allows non-blocking execution, making it suitable for batch processing or integration into web applications.
  • Callback function (recv): Handles responses from the Werk24 server and processes the returned data.
  • Hooks: Define the extraction request (AskMetaData()) and the function to execute when the response is received.
  • Werk24Client(): Manages the connection and request submission.

This approach is ideal for large-scale applications where multiple drawings need to be processed efficiently.

Callback

For seamless integration with web applications or APIs, you can use Werk24's callback-based approach. This allows the server to notify your application when results are ready.

Drawings up to about 4.6 MB

A callback request carries the drawing inside its own body, which limits it to about 4.6 MB. The synchronous and asynchronous approaches upload the drawing separately and take up to 10 MiB. See Drawing File Size Limit.

Producer (Sending Requests)

import asyncio

from werk24 import AskMetaData, Werk24Client


async def read_drawing(path: str):
    """
    Sends a technical drawing to Werk24 for analysis.

    Args:
    ----
    - path (str): Path of the file to process.
    """
    callback_url = "https://<your-own-callback-url>"
    callback_headers = {
        "Authorization": "Bearer XYZ"
    }

    # Specify which information you want to obtain. The results
    # are delivered to your callback URL, so no local hook
    # functions are needed.
    asks = [AskMetaData()]

    # Open the file and send it for processing
    with open(path, "rb") as fid:
        async with Werk24Client() as client:
            request_id = await client.read_drawing_with_callback(
                fid, asks, callback_url, callback_headers=callback_headers
            )
            print(f"Sent request with id: {request_id}")

# Run the asynchronous function
asyncio.run(read_drawing("<path>"))

Explanation

  • Callback URL: Defines where Werk24 should send results when processing is complete.
  • Authorization Headers: Secure the API with a token.
  • Non-blocking processing: The client submits the request and moves on, instead of waiting.

Consumer

import fastapi
from werk24 import TechreadMessage

app = fastapi.FastAPI()

@app.post("/werk24-callback")
def werk24_callback(message:TechreadMessage):
    request_id = message.request_id

    if message.is_successful:
        print(f"Request with request_id={request_id} triggered callback")
        print(message)
    else:
        print(f"Request with request_id={request_id} failed. Exceptions: {message.exceptions}")

Explanation

  • FastAPI Endpoint (/werk24-callback): Handles incoming responses from Werk24.
  • TechreadMessage: The structured response containing extracted data.
  • Logs and error handling: Prints success or failure details for each request.

Checking system status

Before sending drawings, you can verify that the Werk24 API is available:

import asyncio
from werk24 import Werk24Client

async def show_status():
    status = await Werk24Client.get_system_status()
    print(status.status_indicator)
    if status.status_description:
        print(status.status_description)

asyncio.run(show_status())

The returned SystemStatus model provides a high-level indicator such as "ok" along with optional details.

For guidance on integrating these checks into uptime dashboards or alerts, see System Status Monitoring.