Skip to content

Python Client for PDF Generator API (Autogenerated from OpenAPI v3)

Notifications You must be signed in to change notification settings

pdfgeneratorapi/python-client

Repository files navigation

pdf-generator-api

Introduction

PDF Generator API allows you easily generate transactional PDF documents and reduce the development and support costs by enabling your users to create and manage their document templates using a browser-based drag-and-drop document editor.

The PDF Generator API features a web API architecture, allowing you to code in the language of your choice. This API supports the JSON media type, and uses UTF-8 character encoding.

Base URL

The base URL for all the API endpoints is https://us1.pdfgeneratorapi.com/api/v4

For example

  • https://us1.pdfgeneratorapi.com/api/v4/templates
  • https://us1.pdfgeneratorapi.com/api/v4/workspaces
  • https://us1.pdfgeneratorapi.com/api/v4/templates/123123

Editor

PDF Generator API comes with a powerful drag & drop editor that allows to create any kind of document templates, from barcode labels to invoices, quotes and reports. You can find tutorials and videos from our Support Portal.

Definitions

Organization

Organization is a group of workspaces owned by your account.

Workspace

Workspace contains templates. Each workspace has access to their own templates and organization default templates.

Master Workspace

Master Workspace is the main/default workspace of your Organization. The Master Workspace identifier is the email you signed up with.

Default Template

Default template is a template that is available for all workspaces by default. You can set the template access type under Page Setup. If template has "Organization" access then your users can use them from the "New" menu in the Editor.

Data Field

Data Field is a placeholder for the specific data in your JSON data set. In this example JSON you can access the buyer name using Data Field {paymentDetails::buyerName}. The separator between depth levels is :: (two colons). When designing the template you don’t have to know every Data Field, our editor automatically extracts all the available fields from your data set and provides an easy way to insert them into the template.

{
    "documentNumber": 1,
    "paymentDetails": {
        "method": "Credit Card",
        "buyerName": "John Smith"
    },
    "items": [
        {
            "id": 1,
            "name": "Item one"
        }
    ]
}

Rate limiting

Our API endpoints use IP-based rate limiting and allow you to make up to 2 requests per second and 60 requests per minute. If you make more requests, you will receive a response with HTTP code 429.

Response headers contain additional values:

Header Description
X-RateLimit-Limit Maximum requests per minute
X-RateLimit-Remaining The requests remaining in the current minute
Retry-After How many seconds you need to wait until you are allowed to make requests

Libraries and SDKs

Postman Collection

We have created a Postman Collection so you can easily test all the API endpoints without developing and code. You can download the collection here.

Client Libraries

All our Client Libraries are auto-generated using OpenAPI Generator which uses the OpenAPI v3 specification to automatically generate a client library in specific programming language.

We have validated the generated libraries, but let us know if you find any anomalies in the client code.


Authentication

The PDF Generator API uses JSON Web Tokens (JWT) to authenticate all API requests. These tokens offer a method to establish secure server-to-server authentication by transferring a compact JSON object with a signed payload of your account’s API Key and Secret. When authenticating to the PDF Generator API, a JWT should be generated uniquely by a server-side application and included as a Bearer Token in the header of each request.

Accessing your API Key and Secret

You can find your API Key and API Secret from the Account Settings page after you login to PDF Generator API here.

Creating a JWT

JSON Web Tokens are composed of three sections: a header, a payload (containing a claim set), and a signature. The header and payload are JSON objects, which are serialized to UTF-8 bytes, then encoded using base64url encoding.

The JWT's header, payload, and signature are concatenated with periods (.). As a result, a JWT typically takes the following form:

{Base64url encoded header}.{Base64url encoded payload}.{Base64url encoded signature}

We recommend and support libraries provided on jwt.io. While other libraries can create JWT, these recommended libraries are the most robust.

Header

Property alg defines which signing algorithm is being used. PDF Generator API users HS256. Property typ defines the type of token and it is always JWT.

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The second part of the token is the payload, which contains the claims or the pieces of information being passed about the user and any metadata required. It is mandatory to specify the following claims:

  • issuer (iss): Your API key
  • subject (sub): Workspace identifier
  • expiration time (exp): Timestamp (unix epoch time) until the token is valid. It is highly recommended to set the exp timestamp for a short period, i.e. a matter of seconds. This way, if a token is intercepted or shared, the token will only be valid for a short period of time.
{
  "iss": "ad54aaff89ffdfeff178bb8a8f359b29fcb20edb56250b9f584aa2cb0162ed4a",
  "sub": "[email protected]",
  "exp": 1586112639
}

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that. The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

HMACSHA256(
    base64UrlEncode(header) + "." +
    base64UrlEncode(payload),
    API_SECRET)

Putting all together

The output is three Base64-URL strings separated by dots. The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhZDU0YWFmZjg5ZmZkZmVmZjE3OGJiOGE4ZjM1OWIyOWZjYjIwZWRiNTYyNTBiOWY1ODRhYTJjYjAxNjJlZDRhIiwic3ViIjoiZGVtby5leGFtcGxlQGFjdHVhbHJlcG9ydHMuY29tIn0.SxO-H7UYYYsclS8RGWO1qf0z1cB1m73wF9FLl9RCc1Q

// Base64 encoded header: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
// Base64 encoded payload: eyJpc3MiOiJhZDU0YWFmZjg5ZmZkZmVmZjE3OGJiOGE4ZjM1OWIyOWZjYjIwZWRiNTYyNTBiOWY1ODRhYTJjYjAxNjJlZDRhIiwic3ViIjoiZGVtby5leGFtcGxlQGFjdHVhbHJlcG9ydHMuY29tIn0
// Signature: SxO-H7UYYYsclS8RGWO1qf0z1cB1m73wF9FLl9RCc1Q

Temporary JWTs

You can create a temporary token in Account Settings page after you login to PDF Generator API. The generated token uses your email address as the subject (sub) value and is valid for 15 minutes. You can also use jwt.io to generate test tokens for your API calls. These test tokens should never be used in production applications.


Error codes

Code Description
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
422 Unprocessable Entity
429 Too Many Requests
500 Internal Server Error

401 Unauthorized

Description
Authentication failed: request expired
Authentication failed: workspace missing
Authentication failed: key missing
Authentication failed: property 'iss' (issuer) missing in JWT
Authentication failed: property 'sub' (subject) missing in JWT
Authentication failed: property 'exp' (expiration time) missing in JWT
Authentication failed: incorrect signature

402 Payment Required

Description
Your account is suspended, please upgrade your account

403 Forbidden

Description
Your account has exceeded the monthly document generation limit.
Access not granted: You cannot delete master workspace via API
Access not granted: Template is not accessible by this organization
Your session has expired, please close and reopen the editor.

404 Entity not found

Description
Entity not found
Resource not found
None of the templates is available for the workspace.

422 Unprocessable Entity

Description
Unable to parse JSON, please check formatting
Required parameter missing
Required parameter missing: template definition not defined
Required parameter missing: template not defined

429 Too Many Requests

Description
You can make up to 2 requests per second and 60 requests per minute.

This Python package is automatically generated by the OpenAPI Generator project:

  • API version: 4.0.4
  • Package version: 1.0.0
  • Build package: org.openapitools.codegen.languages.PythonClientCodegen For more information, please visit https://support.pdfgeneratorapi.com

Requirements.

Python >=3.7

Migration from other generators like python and python-legacy

Changes

  1. This generator uses spec case for all (object) property names and parameter names.
    • So if the spec has a property name like camelCase, it will use camelCase rather than camel_case
    • So you will need to update how you input and read properties to use spec case
  2. Endpoint parameters are stored in dictionaries to prevent collisions (explanation below)
    • So you will need to update how you pass data in to endpoints
  3. Endpoint responses now include the original response, the deserialized response body, and (todo)the deserialized headers
    • So you will need to update your code to use response.body to access deserialized data
  4. All validated data is instantiated in an instance that subclasses all validated Schema classes and Decimal/str/list/tuple/frozendict/NoneClass/BoolClass/bytes/io.FileIO
    • This means that you can use isinstance to check if a payload validated against a schema class
    • This means that no data will be of type None/True/False
      • ingested None will subclass NoneClass
      • ingested True will subclass BoolClass
      • ingested False will subclass BoolClass
      • So if you need to check is True/False/None, instead use instance.is_true_oapg()/.is_false_oapg()/.is_none_oapg()
  5. All validated class instances are immutable except for ones based on io.File
    • This is because if properties were changed after validation, that validation would no longer apply
    • So no changing values or property values after a class has been instantiated
  6. String + Number types with formats
    • String type data is stored as a string and if you need to access types based on its format like date, date-time, uuid, number etc then you will need to use accessor functions on the instance
    • type string + format: See .as_date_oapg, .as_datetime_oapg, .as_decimal_oapg, .as_uuid_oapg
    • type number + format: See .as_float_oapg, .as_int_oapg
    • this was done because openapi/json-schema defines constraints. string data may be type string with no format keyword in one schema, and include a format constraint in another schema
    • So if you need to access a string format based type, use as_date_oapg/as_datetime_oapg/as_decimal_oapg/as_uuid_oapg
    • So if you need to access a number format based type, use as_int_oapg/as_float_oapg
  7. Property access on AnyType(type unset) or object(dict) schemas
    • Only required keys with valid python names are properties like .someProp and have type hints
    • All optional keys may not exist, so properties are not defined for them
    • One can access optional values with dict_instance['optionalProp'] and KeyError will be raised if it does not exist
    • Use get_item_oapg if you need a way to always get a value whether or not the key exists
      • If the key does not exist, schemas.unset is returned from calling dict_instance.get_item_oapg('optionalProp')
      • All required and optional keys have type hints for this method, and @typing.overload is used
      • A type hint is also generated for additionalProperties accessed using this method
    • So you will need to update you code to use some_instance['optionalProp'] to access optional property and additionalProperty values
  8. The location of the api classes has changed
    • Api classes are located in your_package.apis.tags.some_api
    • This change was made to eliminate redundant code generation
    • Legacy generators generated the same endpoint twice if it had > 1 tag on it
    • This generator defines an endpoint in one class, then inherits that class to generate apis by tags and by paths
    • This change reduces code and allows quicker run time if you use the path apis
      • path apis are at your_package.apis.paths.some_path
    • Those apis will only load their needed models, which is less to load than all of the resources needed in a tag api
    • So you will need to update your import paths to the api classes

Why are Oapg and _oapg used in class and method names?

Classes can have arbitrarily named properties set on them Endpoints can have arbitrary operationId method names set For those reasons, I use the prefix Oapg and _oapg to greatly reduce the likelihood of collisions on protected + public classes/methods. oapg stands for OpenApi Python Generator.

Object property spec case

This was done because when payloads are ingested, they can be validated against N number of schemas. If the input signature used a different property name then that has mutated the payload. So SchemaA and SchemaB must both see the camelCase spec named variable. Also it is possible to send in two properties, named camelCase and camel_case in the same payload. That use case should be support so spec case is used.

Parameter spec case

Parameters can be included in different locations including:

  • query
  • path
  • header
  • cookie

Any of those parameters could use the same parameter names, so if every parameter was included as an endpoint parameter in a function signature, they would collide. For that reason, each of those inputs have been separated out into separate typed dictionaries:

  • query_params
  • path_params
  • header_params
  • cookie_params

So when updating your code, you will need to pass endpoint parameters in using those dictionaries.

Endpoint responses

Endpoint responses have been enriched to now include more information. Any response reom an endpoint will now include the following properties: response: urllib3.HTTPResponse body: typing.Union[Unset, Schema] headers: typing.Union[Unset, TODO] Note: response header deserialization has not yet been added

Installation & Usage

pip install

If the python package is hosted on a repository, you can install directly using:

pip install git+https://github.com/pdfgeneratorapi/python-client.git

(you may need to run pip with root permission: sudo pip install git+https://github.com/pdfgeneratorapi/python-client.git)

Then import the package:

import pdf_generator_api_client

Setuptools

Install via Setuptools.

python setup.py install --user

(or sudo python setup.py install to install the package for all users)

Then import the package:

import pdf_generator_api_client

Getting Started

Please follow the installation procedure and then run the following:

import time
import pdf_generator_api_client
from pprint import pprint
from pdf_generator_api_client.apis.tags import conversion_api
# Defining the host is optional and defaults to https://us1.pdfgeneratorapi.com/api/v4
# See configuration.py for a list of all supported configuration parameters.
configuration = pdf_generator_api_client.Configuration(
    host = "https://us1.pdfgeneratorapi.com/api/v4"
)

# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.

# Configure Bearer authorization (JWT): JSONWebTokenAuth
configuration = pdf_generator_api_client.Configuration(
    access_token = 'YOUR_BEARER_TOKEN'
)

# Enter a context with an instance of the API client
with pdf_generator_api_client.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = conversion_api.ConversionApi(api_client)
    any_type = dict(
        content="<html><title>Test</title><body><h1>Hello world</h1></body></html>",
        paper_size="a4",
        orientation="portrait",
        output="base64",
        filename="Invoice 12345",
    ) # anyType | 

    try:
        # HTML to PDF
        api_response = api_instance.convert_html2_pdf(any_type)
        pprint(api_response)
    except pdf_generator_api_client.ApiException as e:
        print("Exception when calling ConversionApi->convert_html2_pdf: %s\n" % e)

Documentation for API Endpoints

All URIs are relative to https://us1.pdfgeneratorapi.com/api/v4

Class Method HTTP request Description
ConversionApi convert_html2_pdf post /conversion/html2pdf HTML to PDF
ConversionApi convert_url2_pdf post /conversion/url2pdf URL to PDF
DocumentsApi generate_document post /documents/generate Generate document
DocumentsApi generate_document_asynchronous post /documents/generate/async Generate document (async)
DocumentsApi generate_document_batch post /documents/generate/batch Generate document (batch)
DocumentsApi generate_document_batch_asynchronous post /documents/generate/batch/async Generate document (batch + async)
DocumentsApi get_documents get /documents Get documents
TemplatesApi copy_template post /templates/{templateId}/copy Copy template
TemplatesApi create_template post /templates Create template
TemplatesApi delete_template delete /templates/{templateId} Delete template
TemplatesApi get_template get /templates/{templateId} Get template
TemplatesApi get_template_data get /templates/{templateId}/data Get template data fields
TemplatesApi get_templates get /templates Get templates
TemplatesApi open_editor post /templates/{templateId}/editor Open editor
TemplatesApi update_template put /templates/{templateId} Update template
WorkspacesApi create_workspace post /workspaces Create workspace
WorkspacesApi delete_workspace delete /workspaces/{workspaceIdentifier} Delete workspace
WorkspacesApi get_workspace get /workspaces/{workspaceIdentifier} Get workspace
WorkspacesApi get_workspaces get /workspaces Get workspaces

Documentation For Models

Documentation For Authorization

Authentication schemes defined for the API:

JSONWebTokenAuth

  • Type: Bearer authentication (JWT)

Author

[email protected] [email protected] [email protected] [email protected]

Notes for Large OpenAPI documents

If the OpenAPI document is large, imports in pdf_generator_api_client.apis and pdf_generator_api_client.models may fail with a RecursionError indicating the maximum recursion limit has been exceeded. In that case, there are a couple of solutions:

Solution 1: Use specific imports for apis and models like:

  • from pdf_generator_api_client.apis.default_api import DefaultApi
  • from pdf_generator_api_client.model.pet import Pet

Solution 1: Before importing the package, adjust the maximum recursion limit as shown below:

import sys
sys.setrecursionlimit(1500)
import pdf_generator_api_client
from pdf_generator_api_client.apis import *
from pdf_generator_api_client.models import *

About

Python Client for PDF Generator API (Autogenerated from OpenAPI v3)

Resources

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages