Powerful Custom Solutions with Printify’s API

Powerful Custom Solutions with Printify’s API

What is an API?

According to IBM the API definition is:

“An application programming interface, or API, enables companies to open up their applications’ data and functionality to external third-party developers, business partners, and internal departments within their companies.

This allows services and products to communicate with each other and leverage each other’s data and functionality through a documented interface.”

The API in Simple Terms

Simply put, an API is a messenger that takes your request and its details, communicates it to a system and brings back a response to you with the specific data you need.

The Restaurant Analogy

To further simplify the above definition, it’s useful to look at the classic restaurant analogy.

Let’s assume you’re at your favorite pizza restaurant and you’d like to order a pizza. Now, you cannot go into the kitchen and start cooking it yourself.

What will happen is that you will take a look at the menu, find the item you need with the ingredients you like, and give your order to the waiter. Your order is your request.

The waiter (the API), then heads back to the kitchen (the system), passes your order (your request) down to the professional cooking staff and a while later, returns with the pizza you ordered (data in need).

An API Example in Real Life

APIs are utilized almost everywhere in our daily internet interactions. One of the most common examples is when you’re booking your flight via a website such as Kayak, Expedia, or Scyscanner.

When you’re on a flight-booking website, you’d like to see all available flights. So you input details such as flight date, destination, round or one-way trip and you hit “Search”.

Once you hit the search button, an API will take your request and its details, communicate with all the airlines and return a list of available flights that match your needs.

This way you don’t have to go into each airline’s unique website and search for matching flights.

Technical Applications - Use Cases

In this section, we go over several applications of Printify’s API that you can use in your own online business to further its capabilities. 

Below, you can find the explanation of each use case as well as sample codebases that can give a developer some insight on how the Printify API can be practically applied.

Feel free to share this information with an API Developer if you’d like to see how to implement these solutions to your store.

Order Management/Routing sample code

If you’re managing several stores at once, and/or have a large order volume, you can use an API to route your order traffic in whichever direction you need and get all that data in a single place for improved monitoring and management.

In short, managing orders becomes easier with API. 

To do that, we build up a standard HTTP client with OAuth and add your shop as the order endpoint.

We will return the 10 latest orders to call for another page with the next link.

If you want to get only fulfilled orders, add a query parameter for status=fulfilled to the request.

The returned orders will contain everything needed for their analysis or routing into your custom system.

Below is the sample codebase on how to achieve this functionality in PHP:

				
					class PrintifyOrders {
    public function __construct(private \GuzzleHttp\Client $client, private string $accessToken) {}

    public function getShopOrders(int $shopId, bool $fulfilled = false): array {
        $orders = [];
        $endpointUrl = "/v1/shops/$shopId/orders.json";
        $options = [
            'headers' => ['Authorization' => 'Bearer '.$this->accessToken],
            'query'   => ['page' => 1] + ($fulfilled ? ['status' => 'fulfilled'] : []),
        ];

        do {
            [$newOrders, $nextPage] = $this->parseResponse($this->client->get($endpointUrl, $options));
            foreach ($newOrders as $order) {
                $orders[] = $order;
            }
            $options['query']['page'] = $nextPage;
        } while (null !== $nextPage);

        return $orders;
    }

    private function parseResponse(\Psr\Http\Message\ResponseInterface $response): array {
        $data = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);

        return [$data['data'], $data['current_page'] < $data['last_page'] ? $data['current_page'] + 1 : null];
    }
}

class OrdersManager {
    public function __construct(private PrintifyOrders $printifyOrders) {}

    public function customAnalysis(int $shopId): void {
        $orders = $this->printifyOrders->getShopOrders($shopId, fulfilled: true);

        foreach ($orders as $order) {
            // custom analysis script
        }
    }
}

class OrdersRouter {
    public function __construct(private \GuzzleHttp\Client $client, private PrintifyOrders $printifyOrders) {}

    public function routeOrders(int $shopId, string $route): void {
        $orders = $this->printifyOrders->getShopOrders($shopId);

        foreach ($orders as $order) {
            $this->client->post($route, ['body' => json_encode($order, JSON_THROW_ON_ERROR)]);
        }
    }
}

				
			

Product Management sample code

Are you moving a large portfolio of designs to Printify or maybe you’re aiming to simultaneously launch a new collection of products on top of your existing product line? 

Then using API to carry out this process would save you the time and hassle of completing a number of steps manually, while limiting the chance for errors.

You have to call just a few endpoints for changing designs on multiple products.

First, you have to upload your new design and store its unique ID.

Then for each of the products you want to change the design, you have to update their print area placeholders.

If you’re satisfied with the changes, you can publish the product changes to your store.

Below is the sample codebase how to achieve this functionality in PHP:

				
					class PrintifyClient
{
    public function __construct(private \GuzzleHttp\Client $client, private string $accessToken) {}

    public function request(string $method, string $uri = '', array $data = []): array {
        $options = ['headers' => ['Authorization' => 'Bearer '.$this->accessToken]];
        if (!empty($data)) {
            $options['json'] = $data;
        }

        $response = $this->client->request($method, $uri, $options);

        return json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
    }
}

class PrintifyImage
{
    public function __construct(private PrintifyClient $client) {}

    public function uploadImage(string $filename, string $url): string {
        $data = $this->client->request('POST', '/v1/uploads/images.json', ['file_name' => $filename, 'url' => $url]);

        return $data['id'];
    }
}

class PrintifyProduct
{
    public function __construct(private PrintifyClient $client) {}

    public function replaceImage(int $shopId, string $productId, string $imageId): void {
        $productUri = "/v1/shops/$shopId/products/$productId.json";

        $data = $this->client->request('GET', $productUri);

        $data['print_areas'][0]['placeholders'][0]['images'][0]['id'] = $imageId;

        $this->client->request('PUT', $productUri, $data);
    }

    public function publishProduct(int $shopId, string $productId): void {
        $data = ['title' => true, 'description' => true, 'images' => true, 'variants' => true, 'tags' => true];
        $this->client->request('POST', "/v1/shops/$shopId/products/$productId/publish.json", $data);
    }
}

				
			

Product Information Export sample code

As any business, you need to make decisions based on data. 

With an API solution, Printify can offer you access to as much low-level data as possible. This way, you can analyze it all and determine the best course of action for continued business growth and success of your ideas.

To export product-related information about orders, you can call the order endpoints with your product SKU as a query filter. 

Returned data will contain all orders with at least one product with passed SKU.

Next, you can filter out the unneeded products and export that data to a CSV file that contains all the information about the order, product, potential sales and delivery information.

Below is the sample codebase how to achieve this functionality in PHP:

				
					class PrintifyProductOrders {
    public function __construct(private \GuzzleHttp\Client $client, private string $accessToken) {}

    public function getShopOrdersForProduct(int $shopId, string $sku): array {
        $orders = [];
        $endpointUrl = "/v1/shops/$shopId/orders.json";
        $options = [
            'headers' => ['Authorization' => 'Bearer '.$this->accessToken],
            'query'   => ['page' => 1, 'sku' => $sku],
        ];

        do {
            [$newOrders, $nextPage] = $this->parseResponse($this->client->get($endpointUrl, $options));
            foreach ($newOrders as $order) {
                $orders[] = $order;
            }
            $options['query']['page'] = $nextPage;
        } while (null !== $nextPage);


        return $this->filterProductsWithSku($orders, $sku);
    }

    private function parseResponse(\Psr\Http\Message\ResponseInterface $response): array {
        $data = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);

        return [$data['data'], $data['current_page'] < $data['last_page'] ? $data['current_page'] + 1 : null];
    }

    private function filterProductsWithSku(array $orders, string $sku): array {
        foreach ($orders as $orderIndex => $order) {
            foreach ($order['line_items'] as $itemIndex => $item) {
                if ($sku !== $item['metadata']['sku']) {
                    unset($orders[$orderIndex]['line_items'][$itemIndex]);
                }
            }
        }

        return $orders;
    }
}

class ProductInformationExport {
    public function __construct(private PrintifyProductOrders $printifyOrders) {}

    public function export(string $filename, int $shopId, string $sku): void {
        $orders = $this->printifyOrders->getShopOrdersForProduct($shopId, $sku);

        $file = fopen($filename, 'wb');
        fputcsv(
            $file,
            [
                'shop_id',
                'sku',
                'order_id',
                'quantity',
                'shipping_cost',
                'cost',
                'price',
                'sold',
                'shipments_carrier',
                'country',
                'city',
                'email',
                'phone',
                'created_at',
                'sent_to_production_at',
                'fulfilled_at',
            ]
        );
        foreach ($orders as $order) {
            $item = current($order['line_items']);
            fputcsv($file,
                [
                    $shopId,
                    $sku,
                    $order['id'],
                    $item['quantity'],
                    $item['shipping_cost'],
                    $item['cost'],
                    $item['metadata']['price'],
                    'fulfilled' === $item['status'] ? 'YES' : 'NO',
                    $order['shipments']['carrier'] ?? '',
                    $order['address_to']['country'],
                    $order['address_to']['city'],
                    $order['address_to']['email'],
                    $order['address_to']['phone'],
                    $order['created_at'],
                    $item['sent_to_production_at'] ?? '',
                    $item['fulfilled_at'] ?? '',
                ]
            );
        }
        fclose($file);
    }
}

				
			

Make It Happen Today!

Share the article

Topics

Comments

Write a comment