Skip to content

Getting Started

PDFCompose.com provides a REST API which can be used to generate PDF documents in a batch. It uses a HTML template document containing variable placeholders which is filled in with your data. CSS is used to style the PDF as per your requirements.

The pre-requisite to this process is connecting to our servers and authenticating yourself properly. This procedure is covered by this document.

Authentication

Authentication is required to let our servers know who you are and that you have appropriate access to perform the requested operation. To this end, we use a technology called JSON Web Tokens (or JWT) for authentication.

JWT is an internet standard using Public Key Infrastructure (or PKI) to convey information between two parties, typically a server and a client. The server in this case is PDFCompose.com's API servers and the client is your program running on your computers. It works as follows:

  • A user creates an account on PDFCompose.com. He logs in and then requests an API key from the server to be able to use the API from a program.

  • The server creates a data package encapsulating the user's identity, cryptographically signs it with its private key. This signed package is then given to the requesting user as proof of his identity.

  • This data package, called JWT needs to be securely stored by the user and used when needing to prove his identity to the server. The user programs this key into his software so the software client can identify itself to the server.

  • The server then allows access to protected API methods.

This is, in brief, how JWT works in the real world.

Let us now look into how you can obtain an JWT token from our servers.

Creating a JWT token from the website

There are multiple ways of obtaining a JWT authentication token from PDFCompose.com. The first method we will look at is using the website.

  • Login to your account on PDFCompose.com, click the My Account button in the header.

  • A menu drops down and you can create an authentication JWT token by choosing *Show API Token" from the menu.

  • A dialog appears and shows your authentication token. Copy it and store it in a secure location. We show you how to use this token below.

  • Note that this method shows only the Access Token which is valid for about 5 minutes. To keep using this token, you will also need a Refresh Token which we show in the next section (using the API).

Using API to create a JWT token

You can also use the API with your username and password to create a JWT authentication token. The token is required for accessing all other API methods but the token retrieval API method needs to be invoked using your username and password created from the PDFCompose.com website.

Here is how you can create an API token using the curl program available on most platforms (you may need to install it if not available).

curl -v -H "Content-type: application/json" \
        -d '{"username":"xxx@yyy.com","password":"xyxyxy"}' \
        "https://pdfcompose.com/api/authtoken/"

The arguments to curl are:

  • -H specifies that the content being posted is JSON
  • -d specifies the username and password being posted as JSON.
  • -v' specifies thatcurl` show verbose output. Helpful in case of errors.

And here is the response from the server showing the JWT auth token (under the access key) and the refresh token (under the refresh key). See below for details on the refresh token.

{"access": "xxx.yyy.zzz", "refresh": "aaa.bbb.ccc"}

Here we show the code for retreiving the JWT auth token using python requests module.

import requests

resp = requests.post("https://pdfcompose.com/api/authtoken/",
                     data={ "username": "xxx@yyy.com",
                            "password": "xyxyxy" })
resp.raise_for_status()
print(resp.text)

And the response from the server is shown as:

{"access": "xxx.yyy.zzz", "refresh": "aaa.bbb.ccc"}

Here is Java code which will retrieve the JWT access key as well as the refresh key from the server. It uses the username and password to your account on the server.

import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.HashMap;

public class sample
{
    static public void main(String[] args) throws Exception
    {
        URL url = new URL("https://pdfcompose.com/api/authtoken/");
        Map<String,String> params = new HashMap<>();
        params.put("username", "jacobholapage@gmail.com");
        params.put("password", "gnjRDdhSRN6t2NJRo5cd");
        StringBuilder sbuf = new StringBuilder();
        for (Map.Entry<String,String> entry : params.entrySet()) {
            if ( sbuf.length() > 0 ) sbuf.append('&');
            sbuf.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                .append('=')
                .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        byte[] postData = sbuf.toString().getBytes("UTF-8");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        con.setDoOutput(true);
        try(OutputStream out = con.getOutputStream()) {
            out.write(postData);
        }
        try(InputStreamReader in = new InputStreamReader(con.getInputStream())) {
            char[] chars = new char[2048];
            int len;
            while ((len = in.read(chars, 0, chars.length)) != -1) {
                System.out.print(new String(chars, 0, len));
            }
        }
    }
}

The refresh token

The JWT access token received from the server is valid for about 5 minutes. Which means it must be refreshed to be able to use it after that time. Attempting to use it after expiry returns an error message which looks something like this:

{"detail":"Given token not valid ...",...}

Once this happens (or even before), the token can be refreshed. It is done by performing a POST request with the refresh part as a parameter to the URL https://pdfcompose.com/api/authtoken/refresh/ as follows:

Perform a POST using the refresh token with curl as follows:

curl -v -d refresh="aaa.bbb.ccc" \
        "https://pdfcompose.com/api/authtoken/refresh/"

The response assuming everything is correct is similar to when we did the first time authentication:

{"access": "xxx.yyy.zzz", "refresh": "aaa.bbb.xxx"}

Similar to the way we obtained the initial JWT auth token, the code for refreshing a token in python is as follows:

import requests

resp = requests.post("https://pdfcompose.com/api/authtoken/refresh/",
                     data={ "refresh": "aaa.bbb.ccc" })
resp.raise_for_status()
print(resp.text)

You can now proceed to use the access part of the token once again.

Using the JWT access token

Once you have obtained the JWT access token, you can access protected API methods by passing in the token in a HTTP header field called Authorization. In the following example, we request the list of PDF documents in our account using the API endpoint https://pdfcompose.com/api/pdfdoc/.

We pass the access token in the Authorization header in the format Bearer xxx.yyy.zzz where xxx.yyy.zzz is your access token.

curl -v -H "Authorization: Bearer xxx.yyy.zzz" \
        "https://pdfcompose.com/api/pdfdoc/"

The method returns a list of PDF documents in your account.

We use the requests module to make a GET request on the URL for listing documents as follows:

import requests

resp = requests.get("https://pdfcompose.com/api/pdfdoc/",
                    headers={ "Authorization": 'Bearer xxx.yyy.zzz' })
resp.raise_for_status()
print(resp.text)

Conclusion

In this article, we have covered all aspects of getting started with the PDFCompose.com API. We looked at authentication using JWT and how to invoke the authentication methods. Once we get the access key, we noted how to invoke a sample API method.