Code samples

Code samples to get you started quickly with Ruby, Python, PHP and Node.js.

Ruby (using standard library)

This Ruby example creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

require "uri"
require "net/http"

endpoint = URI.parse("https://api.paperplane.app/jobs")
http = Net::HTTP.new(endpoint.host, endpoint.port)
http.use_ssl = true

request = Net::HTTP::Post.new(endpoint.request_uri)
request.basic_auth(ENV.fetch("PAPERPLANE_API_KEY"), "")
request.set_form_data(
  "url" => "https://en.wikipedia.org/wiki/Airplane",
  "page_size" => "A4"
)

response = http.request(request)
puts response.body

Ruby (using the HTTP gem)

This Ruby example uses the HTTP gem which provides a more convenient API than the standard library packages.

# gem install http

require "http"

response = HTTP.basic_auth(user: ENV.fetch("PAPERPLANE_API_KEY"), pass: "").post(
  "https://api.paperplane.app/jobs",
  json: { url: "https://en.wikipedia.org/wiki/Airplane", page_size: "A4" }
)

puts response.body

Python

This Python example creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

The requests library is used for making HTTP requests, so you'll need to have that installed.

# pip install requests

import os
import requests

response = requests.post(
    'https://api.paperplane.app/jobs',
    auth=(os.getenv('PAPERPLANE_API_KEY'), ''),
    data={'url': 'https://en.wikipedia.org/wiki/Airplane', 'page_size': 'A4'}
)

print(response.json())

PHP

This example creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.paperplane.app/jobs',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => array(
    'url' => 'https://en.wikipedia.org/wiki/Airplane',
    'page_size' => 'A4'
  ),
  CURLOPT_USERNAME => getenv('PAPERPLANE_API_KEY')
));

$response = curl_exec($curl);

curl_close($curl);

echo $response;

?>

Node.js

This snippet creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

This example uses the node-fetch library for making HTTP requests.

// npm install node-fetch

const fetch = require("node-fetch");

const url = "https://api.paperplane.app/jobs";

async function createPdf() {
  const auth = new Buffer(process.env.PAPERPLANE_API_KEY + ":").toString(
    "base64"
  );
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Basic ${auth}`
    },
    body: JSON.stringify({
      url: "https://en.wikipedia.org/wiki/Airplane",
      page_size: "A4"
    })
  });
  const json = await response.json();
  console.log(json);
};

createPdf();

Java

This snippet creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

This example uses the Apache HttpComponents library for making HTTP requests.

package com.mycompany.app;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class App {
    public static void main(String[] args) {
        try {
            // Construct the auth header.
            String apiKey = System.getenv("PAPERPLANE_API_KEY");
            String auth = apiKey + ":";
            byte[] authEncoded = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
            String authHeader = "Basic " + new String(authEncoded);
            HttpPost request = new HttpPost("https://api.paperplane.app/jobs");
            request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

            // Create form data to specify our URL and set some options.
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("url", "https://en.wikipedia.org/wiki/Airplane"));
            params.add(new BasicNameValuePair("page_size", "A4"));
            request.setEntity(new UrlEncodedFormEntity(params));

            // Make the POST request.
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            System.out.println(response.getStatusLine().getStatusCode());
            System.out.println(body);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

C# (.NET Core)

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace paperplane
{
  class Example
  {
    class Job
    {
      [JsonPropertyName("url")]
      public string Url { get; set; }

      // ... add further properties here as required.
    }
    static async Task Main()
    {
      try
      {
        // Grab the API key from the environment.
        string apiKey = Environment.GetEnvironmentVariable("PAPERPLANE_API_KEY");
        if (apiKey is null)
        {
          Console.WriteLine("API key not set");
          return;
        }

        // Create a value which will be used for HTTP basic authentication.
        var auth = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(apiKey + ":"));

        // Set up a new HTTP client.
        var http = new HttpClient();
        http.BaseAddress = new Uri("https://api.paperplane.app");
        http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);

        // Create a JSON string describing a new job.
        var job = new Job { Url = "https://example.com" };
        var json = JsonSerializer.Serialize(job);

        // Post to the jobs endpoint.
        var request = new HttpRequestMessage(HttpMethod.Post, "/jobs");
        request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
        var response = await http.SendAsync(request);
        var body = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Response status code: {0}", response.StatusCode);
        Console.WriteLine(body);
      }
      catch (HttpRequestException e)
      {
        Console.WriteLine("Exception: {0} ", e.Message);
      }
    }
  }
}

Go

This snippet creates creates a new PDF job. It reads the API key from the PAPERPLANE_API_KEY environment variable, so make sure you have that configured.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
)

func main() {
	apiKey := os.Getenv("PAPERPLANE_API_KEY")
	endpoint := "https://api.paperplane.app/jobs"
	formData := url.Values{
		"url":       {"https://en.wikipedia.org/wiki/Airplane"},
		"page_size": {"A4"},
	}.Encode()

	// Construct the request
	req, err := http.NewRequest("POST", endpoint, strings.NewReader(formData))
	if err != nil {
		log.Fatal(err)
	}
	req.SetBasicAuth(apiKey, "")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	// Send the request
	client := http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("response status:", resp.Status)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return
	}
	fmt.Println(string(body))
}

Other languages

We will gradually be adding examples for other languages here. If there’s a specific language you’d like an example for, please get in touch and let us know.

Last updated