The Templates endpoints
The endpoints to deal with templates have this prefix:
https://api.mindthedoc.com/v0/templates
Creating a template
Let's say we want to use MindTheDoc to generate beautiful invoices. We will need an HTML file but also the logo of the supplier of the invoice, and, maybe a CSS file to define the style of the invoice.
First we need to compress those files in a ZIP file.
The ZIP file must contain at least the HTML file at the root of the archive with a ".html" extension.
Create the ZIP file
import io
import zipfile
from pathlib import Path
def zip_content_files(source_dir: Path) -> io.BytesIO:
"""Zip all files inside `source_dir` and return a File."""
dir_iterator = source_dir.rglob("**/*")
files = [f for f in dir_iterator if f.is_file()]
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, mode="w") as archive:
for filepath in files:
archive.writestr(
data=filepath.read_bytes(),
zinfo_or_arcname=str(filepath.relative_to(source_dir)),
)
buffer.seek(0)
return buffer
invoice_dir = Path("./invoice_html")
invoice_zip = zip_content_files(invoice_dir)
invoice_archive = Path("invoice.zip")
invoice_archive.write_bytes(invoice_zip)
Upload the template
Now we send a request with the ZIP file as payload to the templates endpoint to create a new template.
from pathlib import Path
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
# The API token taken from the website
api_token = "123456"
base_url = "https://api.mindthedoc.com/v0"
# Specify the folder where my HTML template is
invoice_archive = Path("templates/invoice.zip")
# This is how we use the API token
session = requests.Session()
session.headers["Authorization"] = f"Token {api_token}"
templates_url = f"{base_url}/templates"
payload = MultipartEncoder(
fields={
'name': "my_invoice",
'type': 'ZIP',
'file': ('my_invoice.zip', invoice_archive.open("rb"), 'text/plain')
}
)
response = session.post(
templates_url,
data=payload,
headers={'Content-Type': payload.content_type},
)
response_data = response.json()
template_id = response_data["id"]
If the response status code is a 201, it means the template has been created. You can fetch the template again by doing a GET request to the endpoint:
response = session.get(f"{templates_url}/{template_id}")
You can also see on your dashboard of the website the my_invoice template.
Now that the template is created, it's time to generate a document out of it.