Skip to content

Commit a765607

Browse files
authored
Add 5 New TypeScript Example Scripts (#22)
* feat(examples): add getCatalogProducts.ts for listing Printful catalog products - Demonstrates fetching and displaying all product names and IDs from the Printful catalog using the SDK. - Includes usage instructions, environment variable setup guidance, and dotenv tip in comments. - Provides sample output and a truncated example of the full API response for reference. - No sensitive data; API token is referenced via placeholder. * feat(examples): add getCatalogVariants.ts for listing product variants - Shows how to fetch and print all variants for a given Printful catalog product. - Displays variant ID, name, size, and color. - Includes usage comments, .env variable requirements, and dotenv tip. - Contains example output and a truncated sample API response. - API token and product ID are placeholders for safe usage. * feat(examples): add getMockupStyles.ts for retrieving mockup styles - Retrieves and prints all available mockup styles for a specific Printful catalog product. - Outputs style ID and descriptive name for each style. - Usage instructions, environment variable setup, and dotenv tip provided in comments. - Includes sample output and a truncated example API response. - All sensitive information is handled via placeholders. * feat(examples): add getMockupStyles.ts for retrieving mockup styles - Retrieves and prints all available mockup styles for a specific Printful catalog product. - Outputs style ID and descriptive name for each style. - Usage instructions, environment variable setup, and dotenv tip provided in comments. - Includes sample output and a truncated example API response. - All sensitive information is handled via placeholders. * feat(examples): add createMockup.ts for generating sticker mockups - Demonstrates creating a mockup generation task for a sticker product and polling for completion. - Prints resulting mockup image URLs upon successful task completion. - Usage comments, required .env variables, and dotenv tip included for best practices. - Contains sample output and a full example of a completed API response. - All sensitive values are placeholders; no secrets are present.
1 parent 1dd2f08 commit a765607

File tree

5 files changed

+1229
-0
lines changed

5 files changed

+1229
-0
lines changed

examples/typescript/createFile.ts

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Usage: npm run start ./createFile.js
2+
// Requires: Set environment variables in a .env file (see README)
3+
// Tip: Use a package like 'dotenv' to automatically load environment variables.
4+
// Example: PRINTFUL_API_TOKEN, STORE_ID, FILE_URL
5+
// Docs: https://spencerlepine.github.io/printful-sdk-js-v2/classes/FilesV2Service.html#addFile
6+
7+
import { PrintfulClient } from 'printful-sdk-js-v2';
8+
import * as path from 'path';
9+
10+
const printful = new PrintfulClient({
11+
TOKEN: '<PRINTFUL_API_TOKEN>', // Use your API token or dotenv
12+
});
13+
14+
const STORE_ID = '<STORE_ID>'; // Your Printful store ID
15+
const FILE_URL = '<FILE_URL>'; // Public PNG file URL
16+
17+
/**
18+
* Uploads a file to Printful and prints the uploaded file ID and details.
19+
*/
20+
(async () => {
21+
try {
22+
// Ensure the file path is a public URL
23+
if (!FILE_URL.startsWith('http://') && !FILE_URL.startsWith('https://')) {
24+
throw new Error('Printful API requires a public URL for file upload. Please provide a valid URL.');
25+
}
26+
27+
// Upload the file to Printful
28+
const uploadResponse = await printful.filesV2.addFile(
29+
{
30+
url: FILE_URL,
31+
filename: path.basename(FILE_URL),
32+
},
33+
STORE_ID
34+
);
35+
36+
const fileData = uploadResponse?.data;
37+
if (!fileData?.id) {
38+
console.error('File upload failed:', uploadResponse);
39+
return;
40+
}
41+
42+
// Print the uploaded file ID and details
43+
console.log('Uploaded file ID:', fileData.id);
44+
console.log('File details:', fileData);
45+
46+
// Optionally, print the full response for debugging
47+
// console.log('Full upload response:', JSON.stringify(uploadResponse, null, 2));
48+
} catch (err) {
49+
console.error('Error uploading file:', err);
50+
}
51+
})();
52+
53+
// Example:
54+
// Uploaded file ID: 818783518
55+
// File details: {
56+
// id: 818783518,
57+
// url: 'https://xkamgjyazjufvmpoorzy.supabase.co/storage/v1/object/public/product-images//sticker_2.png',
58+
// hash: '63a4a96a5bd9de87e4c9bab3777c9f8b',
59+
// filename: 'sticker_2.png',
60+
// mime_type: 'image/png',
61+
// size: 1703202,
62+
// width: 1024,
63+
// height: 1024,
64+
// dpi: 72,
65+
// status: 'ok',
66+
// created: '2025-04-16T11:41:35Z',
67+
// thumbnail_url: 'https://files.cdn.printful.com/files/63a/63a4a96a5bd9de87e4c9bab3777c9f8b_thumb.png',
68+
// preview_url: 'https://files.cdn.printful.com/files/63a/63a4a96a5bd9de87e4c9bab3777c9f8b_preview.png',
69+
// visible: true,
70+
// is_temporary: false,
71+
// _links: { self: { href: 'https://api.printful.com/v2/files/818783518' } }
72+
// }
73+
74+
// Full upload response: {
75+
// "data": {
76+
// "id": 818783518,
77+
// "url": "https://xkamgjyazjufvmpoorzy.supabase.co/storage/v1/object/public/product-images//sticker_2.png",
78+
// "hash": "63a4a96a5bd9de87e4c9bab3777c9f8b",
79+
// "filename": "sticker_2.png",
80+
// "mime_type": "image/png",
81+
// "size": 1703202,
82+
// "width": 1024,
83+
// "height": 1024,
84+
// "dpi": 72,
85+
// "status": "ok",
86+
// "created": "2025-04-16T11:41:35Z",
87+
// "thumbnail_url": "https://files.cdn.printful.com/files/63a/63a4a96a5bd9de87e4c9bab3777c9f8b_thumb.png",
88+
// "preview_url": "https://files.cdn.printful.com/files/63a/63a4a96a5bd9de87e4c9bab3777c9f8b_preview.png",
89+
// "visible": true,
90+
// "is_temporary": false,
91+
// "_links": {
92+
// "self": {
93+
// "href": "https://api.printful.com/v2/files/818783518"
94+
// }
95+
// }
96+
// },
97+
// "extra": []
98+
// }
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
// Usage: npm run start ./createMockup.js
2+
// Requires: Set environment variables in a .env file (see README)
3+
// Tip: Use a package like 'dotenv' to automatically load environment variables.
4+
// Example: PRINTFUL_API_TOKEN, STORE_ID, FILE_ID, CATALOG_PRODUCT_ID, CATALOG_VARIANT_ID, MOCKUP_STYLE_ID
5+
// Docs: https://spencerlepine.github.io/printful-sdk-js-v2/classes/MockupGeneratorV2Service.html#createMockupGeneratorTasks
6+
7+
import { PrintfulClient, MockupTaskCreation } from 'printful-sdk-js-v2';
8+
9+
const printful = new PrintfulClient({
10+
TOKEN: '<PRINTFUL_API_TOKEN>', // Use your API token or dotenv
11+
});
12+
13+
// Replace the following values with your actual Printful data.
14+
const STORE_ID: string = '<STORE_ID>'; // Your Printful store ID f.e. 14045721
15+
const FILE_ID: number = 818783518; // File ID to use in mockup (must be uploaded first)
16+
const CATALOG_PRODUCT_ID: number = 358; // Kiss-Cut Sticker
17+
const CATALOG_VARIANT_ID: number = 10163; // 3x3 Kiss-Cut Sticker
18+
const MOCKUP_STYLE_ID: number = 19000; // Default style
19+
/**
20+
* Generate a sticker mockup for a given file ID.
21+
*
22+
* This script creates a mockup generation task, polls for task completion, and prints the resulting mockup URLs.
23+
*
24+
* Usage:
25+
* 1. Replace the above values with your actual data.
26+
* 2. Run the script using `tsc && node createMockup.ts`.
27+
*/
28+
(async () => {
29+
// Prepare the payload for mockup generation
30+
const payload = {
31+
format: MockupTaskCreation.format.JPG,
32+
products: [
33+
{
34+
source: 'catalog',
35+
catalog_product_id: CATALOG_PRODUCT_ID,
36+
catalog_variant_id: CATALOG_VARIANT_ID,
37+
mockup_style_ids: [MOCKUP_STYLE_ID],
38+
placements: [
39+
{
40+
placement: 'default',
41+
technique: 'sticker',
42+
files: [{ id: FILE_ID, type: 'default' }],
43+
layers: [
44+
{
45+
type: 'file',
46+
id: FILE_ID,
47+
},
48+
],
49+
},
50+
],
51+
},
52+
],
53+
};
54+
55+
try {
56+
// Create the mockup generation task
57+
const response = await printful.mockupGeneratorV2.createMockupGeneratorTasks(STORE_ID, payload);
58+
// Optionally, print the full response for debugging
59+
// console.log('Full mockup task response:', JSON.stringify(response, null, 2));
60+
61+
const taskId = Array.isArray(response?.data) && response.data[0]?.id;
62+
if (!taskId) {
63+
console.error('No mockup task ID returned', response);
64+
return;
65+
}
66+
67+
// Poll for task completion (max 10 tries, 3s interval)
68+
for (let i = 0; i < 10; i++) {
69+
await new Promise(res => setTimeout(res, 3000));
70+
const poll = (await printful.mockupGeneratorV2.httpRequest.request({
71+
method: 'GET',
72+
url: '/v2/mockup-tasks',
73+
query: {
74+
id: [String(taskId)],
75+
limit: 20,
76+
},
77+
headers: {
78+
'X-PF-Store-Id': STORE_ID,
79+
},
80+
})) as any;
81+
const pollData = Array.isArray(poll?.data) ? poll.data : [];
82+
if (pollData.length > 0 && pollData[0].status === 'completed') {
83+
const mockupUrls: string[] = [];
84+
const taskData = pollData[0];
85+
if (taskData.catalog_variant_mockups) {
86+
for (const variant of taskData.catalog_variant_mockups) {
87+
if (variant.mockups) {
88+
for (const mockup of variant.mockups) {
89+
if (mockup.mockup_url) {
90+
mockupUrls.push(mockup.mockup_url);
91+
}
92+
}
93+
}
94+
}
95+
}
96+
console.log('Mockup URLs:', mockupUrls);
97+
// Optionally, print the full completed task data
98+
// console.log('Full completed task:', JSON.stringify(taskData, null, 2));
99+
return;
100+
}
101+
}
102+
console.error('Mockup task did not complete in time.');
103+
} catch (err) {
104+
console.error('Error generating mockup:', err);
105+
}
106+
})();
107+
108+
// Example:
109+
// Mockup URLs: [
110+
// 'https://printful-upload.s3-accelerate.amazonaws.com/tmp/67fbff50f5ae098b8aaef5b10c7edb21/kiss-cut-stickers-white-3x3-default-6800caef9917e.jpg'
111+
// ]
112+
113+
// Full completed task: {
114+
// "id": 775035217,
115+
// "status": "completed",
116+
// "catalog_variant_mockups": [
117+
// {
118+
// "catalog_variant_id": 10163,
119+
// "mockups": [
120+
// {
121+
// "placement": "default",
122+
// "display_name": "Print file",
123+
// "technique": "digital",
124+
// "style_id": 19000,
125+
// "mockup_url": "https://printful-upload.s3-accelerate.amazonaws.com/tmp/76ffb67a625855eb6a3af60a312cc6a1/kiss-cut-stickers-white-3x3-default-6800cb11eca7d.jpg"
126+
// }
127+
// ]
128+
// }
129+
// ],
130+
// "failure_reasons": [],
131+
// "_links": {
132+
// "self": {
133+
// "href": "https://api.printful.com/v2/mockup-tasks?id=775035217"
134+
// }
135+
// }
136+
// }
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// Usage: npm run start ./getCatalogProducts.js
2+
// Requires: Set environment variables in a .env file (see README)
3+
// Tip: Use a package like 'dotenv' to automatically load environment variables.
4+
// Example: PRINTFUL_API_TOKEN
5+
// Docs: https://spencerlepine.github.io/printful-sdk-js-v2/classes/CatalogV2Service.html#getProducts
6+
7+
import { PrintfulClient } from 'printful-sdk-js-v2';
8+
9+
// Replace with your API token or use dotenv
10+
const printful = new PrintfulClient({
11+
TOKEN: '<PRINTFUL_API_TOKEN>', // Use your API token or dotenv
12+
});
13+
14+
/**
15+
* Lists Printful catalog products with names and IDs.
16+
*
17+
* Usage:
18+
* 1. Replace the TOKEN above with your actual Printful API token.
19+
* 2. Run: tsc && node getCatalogProducts.js
20+
*/
21+
(async () => {
22+
try {
23+
const response = await printful.catalogV2.getProducts();
24+
// Optionally, print the full response for debugging
25+
// console.log('Full catalog products response:', JSON.stringify(response, null, 2));
26+
if (!response?.data?.length) {
27+
console.log('No catalog products found.');
28+
return;
29+
}
30+
response.data.forEach((product: { name: string; id: number }) => {
31+
console.log(`${product.name} (ID: ${product.id})`);
32+
});
33+
} catch (err) {
34+
console.error('Error fetching catalog products:', err);
35+
}
36+
})();
37+
38+
//Example Output:
39+
// Enhanced Matte Paper Poster (in) (ID: 1)
40+
// Enhanced Matte Paper Framed Poster (in) (ID: 2)
41+
// Canvas (in) (ID: 3)
42+
// Unisex Basic Softstyle T-Shirt | Gildan 64000 (ID: 12)
43+
// White Glossy Mug (ID: 19)
44+
// Unisex Lightweight T-Shirt | Gildan 980 (ID: 37)
45+
// Men's Long Sleeve Shirt | Gildan 2400 (ID: 57)
46+
// Unisex Staple T-Shirt | Bella + Canvas 3001 (ID: 71)
47+
// Snapback | Otto Cap 125-978 (ID: 77)
48+
// Knit Beanie | Otto Cap 82-480 (ID: 81)
49+
// All-Over Print Basic Pillow (ID: 83)
50+
// All-Over Print Tote Bag (ID: 84)
51+
// All-Over Print Basic Pillow Case (ID: 89)
52+
// Flat Bill Cap | Yupoong 6007 (ID: 91)
53+
// 5 Panel Cap | Yupoong 7005 (ID: 92)
54+
// Pom-Pom Knit Cap | Sportsman SP15 (ID: 93)
55+
// Classic Snapback | Yupoong 6089M (ID: 99)
56+
// 5 Panel Trucker Cap | Yupoong 6006 (ID: 100)
57+
// Men's Fitted T-Shirt | Next Level 3600 (ID: 108)
58+
// Men's Fitted Long Sleeve Shirt | Next Level 3601 (ID: 116)
59+
60+
// Full catalog products response (truncated for brevity):
61+
// {
62+
// "data": [
63+
// {
64+
// "id": 1,
65+
// "type": "POSTER",
66+
// "main_category_id": 55,
67+
// "name": "Enhanced Matte Paper Poster (in)",
68+
// "brand": null,
69+
// "model": "",
70+
// "image": "[https://files.cdn.printful.com/products/1/product_1613463122.jpg",](https://files.cdn.printful.com/products/1/product_1613463122.jpg",)
71+
// "variant_count": 16,
72+
// "is_discontinued": false,
73+
// "description": "Museum-quality posters made on thick matte paper...",
74+
// "sizes": [
75+
// "18″×24″",
76+
// "24″×36″",
77+
// "12″×16″",
78+
// "44″×44″",
79+
// "12″×18″",
80+
// // ...truncated for brevity...
81+
// "A0 (33.1″×46.8″)",
82+
// "27″×40″"
83+
// ],
84+
// "colors": [
85+
// { "name": "Black", "value": "#0b0b0b" },
86+
// { "name": "Heavy Metal", "value": "#454641" },
87+
// { "name": "White", "value": "#ffffff" }
88+
// ],
89+
// "techniques": [
90+
// { "key": "dtg", "display_name": "DTG printing", "is_default": true },
91+
// { "key": "embroidery", "display_name": "Embroidery", "is_default": false }
92+
// ],
93+
// "placements": [
94+
// {
95+
// "placement": "embroidery_chest_left",
96+
// "technique": "embroidery",
97+
// "layers": [
98+
// { "type": "file", "layer_options": [] }
99+
// ],
100+
// "placement_options": [],
101+
// "conflicting_placements": []
102+
// },
103+
// // ...truncated for brevity...
104+
// {
105+
// "placement": "mockup",
106+
// "technique": "dtg",
107+
// "layers": [
108+
// { "type": "file", "layer_options": [] }
109+
// ],
110+
// "placement_options": [],
111+
// "conflicting_placements": []
112+
// }
113+
// ],
114+
// "product_options": [
115+
// {
116+
// "name": "lifelike",
117+
// "techniques": ["dtg"],
118+
// "type": "bool",
119+
// "values": [true, false]
120+
// },
121+
// {
122+
// "name": "notes",
123+
// "techniques": ["dtg", "embroidery", "sublimation", "cut-sew", "fabric"],
124+
// "type": "string",
125+
// "values": ["A simple note"]
126+
// }
127+
// // ...truncated for brevity...
128+
// ],
129+
// "_links": {
130+
// "self": { "href": "[https://api.printful.com/v2/catalog-products/1"](https://api.printful.com/v2/catalog-products/1") },
131+
// "variants": { "href": "[https://api.printful.com/v2/catalog-products/1/catalog-variants"](https://api.printful.com/v2/catalog-products/1/catalog-variants") },
132+
// "categories": { "href": "[https://api.printful.com/v2/catalog-products/1/catalog-categories"](https://api.printful.com/v2/catalog-products/1/catalog-categories") },
133+
// "product_prices": { "href": "[https://api.printful.com/v2/catalog-products/1/prices"](https://api.printful.com/v2/catalog-products/1/prices") },
134+
// "product_sizes": { "href": "[https://api.printful.com/v2/catalog-products/1/sizes"](https://api.printful.com/v2/catalog-products/1/sizes") },
135+
// "product_images": { "href": "[https://api.printful.com/v2/catalog-products/1/images"](https://api.printful.com/v2/catalog-products/1/images") },
136+
// "product_availability": { "href": "[https://api.printful.com/v2/catalog-products/1/availability"](https://api.printful.com/v2/catalog-products/1/availability") }
137+
// }
138+
// },
139+
// {
140+
// "id": 2,
141+
// "type": "POSTER",
142+
// "main_category_id": 55,
143+
// "name": "Enhanced Matte Paper Framed Poster (in)",
144+
// // ...truncated for brevity...
145+
// }
146+
// // ...more products...
147+
// ],
148+
// "paging": { "total": 363, "limit": 20, "offset": 0 },
149+
// "_links": {
150+
// "self": { "href": "[https://api.printful.com/v2/catalog-products?limit=20..."](https://api.printful.com/v2/catalog-products?limit=20...") },
151+
// "next": { "href": "[https://api.printful.com/v2/catalog-products?limit=20...&offset=20"](https://api.printful.com/v2/catalog-products?limit=20...&offset=20") },
152+
// "first": { "href": "[https://api.printful.com/v2/catalog-products?limit=20..."](https://api.printful.com/v2/catalog-products?limit=20...") },
153+
// "last": { "href": "[https://api.printful.com/v2/catalog-products?limit=20...&offset=360"](https://api.printful.com/v2/catalog-products?limit=20...&offset=360") }
154+
// }
155+
// }

0 commit comments

Comments
 (0)