lettr 1.0.0

Official Rust SDK for the Lettr Email API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use std::sync::Arc;

use reqwest::Method;
use serde::{Deserialize, Serialize};

use crate::config::Config;

/// Service for the `/templates` endpoints.
#[derive(Clone, Debug)]
pub struct TemplatesSvc(pub(crate) Arc<Config>);

impl TemplatesSvc {
    /// List email templates with optional pagination.
    ///
    /// If `project_id` is not provided, templates from the team's default project
    /// will be returned.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # use lettr::templates::ListTemplatesOptions;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let options = ListTemplatesOptions::new().per_page(10);
    /// let response = client.templates.list(options).await?;
    ///
    /// for template in &response.templates {
    ///     println!("{}: {} (slug: {})", template.id, template.name, template.slug);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn list(
        &self,
        options: ListTemplatesOptions,
    ) -> crate::Result<ListTemplatesResponse> {
        let mut request = self.0.build(Method::GET, "/templates");

        if let Some(project_id) = options.project_id {
            request = request.query(&[("project_id", project_id.to_string())]);
        }
        if let Some(per_page) = options.per_page {
            request = request.query(&[("per_page", per_page.to_string())]);
        }
        if let Some(page) = options.page {
            request = request.query(&[("page", page.to_string())]);
        }

        let response = self.0.send(request).await?;
        let wrapper = response.json::<ListTemplatesResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Create a new email template.
    ///
    /// Provide either HTML or Topol editor JSON content (but not both).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # use lettr::templates::CreateTemplateOptions;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let template = CreateTemplateOptions::new("Welcome Email")
    ///     .with_html("<h1>Hello {{FIRST_NAME}}!</h1>");
    ///
    /// let result = client.templates.create(template).await?;
    /// println!("Template created: {} (slug: {})", result.id, result.slug);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn create(
        &self,
        options: CreateTemplateOptions,
    ) -> crate::Result<CreateTemplateResponse> {
        let request = self.0.build(Method::POST, "/templates").json(&options);
        let response = self.0.send(request).await?;
        let wrapper = response.json::<CreateTemplateResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Retrieve details of a single template.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let template = client.templates.get("welcome-email", None).await?;
    /// println!("Name: {}, Active version: {:?}", template.name, template.active_version);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn get(&self, slug: &str, project_id: Option<u64>) -> crate::Result<TemplateDetail> {
        let path = format!("/templates/{slug}");
        let mut request = self.0.build(Method::GET, &path);

        if let Some(project_id) = project_id {
            request = request.query(&[("project_id", project_id.to_string())]);
        }

        let response = self.0.send(request).await?;
        let wrapper = response.json::<ShowTemplateResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Update an existing template.
    ///
    /// If `html` or `json` is provided, a new active version will be created.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # use lettr::templates::UpdateTemplateOptions;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let options = UpdateTemplateOptions::new()
    ///     .with_name("Updated Welcome Email")
    ///     .with_html("<h1>Hello {{NAME}}!</h1>");
    ///
    /// let result = client.templates.update("welcome-email", options).await?;
    /// println!("Updated: {}, Version: {}", result.name, result.active_version);
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn update(
        &self,
        slug: &str,
        options: UpdateTemplateOptions,
    ) -> crate::Result<UpdateTemplateResponse> {
        let path = format!("/templates/{slug}");
        let request = self.0.build(Method::PUT, &path).json(&options);
        let response = self.0.send(request).await?;
        let wrapper = response.json::<UpdateTemplateResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Delete a template.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// client.templates.delete("welcome-email", None).await?;
    /// println!("Template deleted.");
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn delete(&self, slug: &str, project_id: Option<u64>) -> crate::Result<()> {
        let path = format!("/templates/{slug}");
        let mut request = self.0.build(Method::DELETE, &path);

        if let Some(project_id) = project_id {
            request = request.query(&[("project_id", project_id.to_string())]);
        }

        self.0.send(request).await?;
        Ok(())
    }

    /// Get merge tags for a template version.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let tags = client.templates.get_merge_tags("welcome-email", None, None).await?;
    /// for tag in &tags.merge_tags {
    ///     println!("{}: required={}", tag.key, tag.required);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn get_merge_tags(
        &self,
        slug: &str,
        project_id: Option<u64>,
        version: Option<u32>,
    ) -> crate::Result<MergeTagsList> {
        let path = format!("/templates/{slug}/merge-tags");
        let mut request = self.0.build(Method::GET, &path);

        if let Some(project_id) = project_id {
            request = request.query(&[("project_id", project_id.to_string())]);
        }
        if let Some(version) = version {
            request = request.query(&[("version", version.to_string())]);
        }

        let response = self.0.send(request).await?;
        let wrapper = response.json::<GetMergeTagsResponseWrapper>().await?;
        Ok(wrapper.data)
    }

    /// Get rendered HTML for a template.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use lettr::Lettr;
    /// # async fn run() -> lettr::Result<()> {
    /// let client = Lettr::new("your-api-key");
    ///
    /// let result = client.templates.get_html(1, "welcome-email").await?;
    /// println!("HTML length: {}", result.html.len());
    /// # Ok(())
    /// # }
    /// ```
    #[maybe_async::maybe_async]
    pub async fn get_html(
        &self,
        project_id: u64,
        slug: &str,
    ) -> crate::Result<GetTemplateHtmlResponse> {
        let mut request = self.0.build(Method::GET, "/templates/html");
        request = request.query(&[
            ("project_id", project_id.to_string()),
            ("slug", slug.to_string()),
        ]);

        let response = self.0.send(request).await?;
        let wrapper = response.json::<GetTemplateHtmlResponseWrapper>().await?;
        Ok(wrapper.data)
    }
}

// ── Request Types ──────────────────────────────────────────────────────────

/// Options for listing templates.
#[must_use]
#[derive(Debug, Default, Clone)]
pub struct ListTemplatesOptions {
    project_id: Option<u64>,
    per_page: Option<u32>,
    page: Option<u32>,
}

impl ListTemplatesOptions {
    /// Creates new [`ListTemplatesOptions`] with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by project ID. If not set, uses the team's default project.
    #[inline]
    pub fn project_id(mut self, project_id: u64) -> Self {
        self.project_id = Some(project_id);
        self
    }

    /// Sets the number of results per page (1-100).
    #[inline]
    pub fn per_page(mut self, per_page: u32) -> Self {
        self.per_page = Some(per_page);
        self
    }

    /// Sets the page number.
    #[inline]
    pub fn page(mut self, page: u32) -> Self {
        self.page = Some(page);
        self
    }
}

/// Options for creating a new template.
#[must_use]
#[derive(Debug, Clone, Serialize)]
pub struct CreateTemplateOptions {
    /// Template name.
    name: String,

    /// HTML content for the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    html: Option<String>,

    /// Topol editor JSON content.
    #[serde(skip_serializing_if = "Option::is_none")]
    json: Option<String>,

    /// Project ID. If not set, uses the team's default project.
    #[serde(skip_serializing_if = "Option::is_none")]
    project_id: Option<u64>,

    /// Folder ID within the project.
    #[serde(skip_serializing_if = "Option::is_none")]
    folder_id: Option<u64>,
}

impl CreateTemplateOptions {
    /// Creates new [`CreateTemplateOptions`] with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            html: None,
            json: None,
            project_id: None,
            folder_id: None,
        }
    }

    /// Sets the HTML content for the template.
    #[inline]
    pub fn with_html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }

    /// Sets the Topol editor JSON content for the template.
    #[inline]
    pub fn with_json(mut self, json: impl Into<String>) -> Self {
        self.json = Some(json.into());
        self
    }

    /// Sets the project ID.
    #[inline]
    pub fn with_project_id(mut self, project_id: u64) -> Self {
        self.project_id = Some(project_id);
        self
    }

    /// Sets the folder ID.
    #[inline]
    pub fn with_folder_id(mut self, folder_id: u64) -> Self {
        self.folder_id = Some(folder_id);
        self
    }
}

/// Options for updating an existing template.
#[must_use]
#[derive(Debug, Default, Clone, Serialize)]
pub struct UpdateTemplateOptions {
    /// Project ID to find the template in.
    #[serde(skip_serializing_if = "Option::is_none")]
    project_id: Option<u64>,

    /// New name for the template.
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,

    /// New HTML content. Creates a new active version.
    #[serde(skip_serializing_if = "Option::is_none")]
    html: Option<String>,

    /// New JSON content for Topol editor. Creates a new active version.
    #[serde(skip_serializing_if = "Option::is_none")]
    json: Option<String>,
}

impl UpdateTemplateOptions {
    /// Creates new [`UpdateTemplateOptions`] with no fields set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the project ID.
    #[inline]
    pub fn with_project_id(mut self, project_id: u64) -> Self {
        self.project_id = Some(project_id);
        self
    }

    /// Sets the new template name.
    #[inline]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the new HTML content.
    #[inline]
    pub fn with_html(mut self, html: impl Into<String>) -> Self {
        self.html = Some(html.into());
        self
    }

    /// Sets the new Topol editor JSON content.
    #[inline]
    pub fn with_json(mut self, json: impl Into<String>) -> Self {
        self.json = Some(json.into());
        self
    }
}

// ── Response Types ─────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ListTemplatesResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: ListTemplatesResponse,
}

/// Response from listing templates.
#[derive(Debug, Clone, Deserialize)]
pub struct ListTemplatesResponse {
    /// List of templates.
    pub templates: Vec<Template>,
    /// Pagination information.
    pub pagination: TemplatePagination,
}

/// An email template.
#[derive(Debug, Clone, Deserialize)]
pub struct Template {
    /// Template ID.
    pub id: u64,
    /// Template name.
    pub name: String,
    /// URL-friendly slug.
    pub slug: String,
    /// Project ID this template belongs to.
    pub project_id: u64,
    /// Folder ID this template belongs to.
    pub folder_id: u64,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

/// Pagination metadata for template list responses.
#[derive(Debug, Clone, Deserialize)]
pub struct TemplatePagination {
    /// Total number of templates.
    pub total: u64,
    /// Results per page.
    pub per_page: u32,
    /// Current page number.
    pub current_page: u32,
    /// Last page number.
    pub last_page: u32,
}

#[derive(Debug, Deserialize)]
struct CreateTemplateResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: CreateTemplateResponse,
}

/// Response from creating a template.
#[derive(Debug, Clone, Deserialize)]
pub struct CreateTemplateResponse {
    /// Template ID.
    pub id: u64,
    /// Template name.
    pub name: String,
    /// URL-friendly slug.
    pub slug: String,
    /// Project ID.
    pub project_id: u64,
    /// Folder ID.
    pub folder_id: u64,
    /// Active version number.
    pub active_version: u32,
    /// Extracted merge tags.
    #[serde(default)]
    pub merge_tags: Vec<MergeTag>,
    /// Creation timestamp.
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
struct ShowTemplateResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: TemplateDetail,
}

/// Detailed template information.
#[derive(Debug, Clone, Deserialize)]
pub struct TemplateDetail {
    /// Template ID.
    pub id: u64,
    /// Template name.
    pub name: String,
    /// URL-friendly slug.
    pub slug: String,
    /// Project ID.
    pub project_id: u64,
    /// Folder ID.
    pub folder_id: u64,
    /// Active version number.
    pub active_version: Option<u32>,
    /// Total number of versions.
    pub versions_count: u32,
    /// HTML content of the active version.
    #[serde(default)]
    pub html: Option<String>,
    /// JSON definition of the active version (for visual editor templates).
    #[serde(default)]
    pub json: Option<String>,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
struct UpdateTemplateResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: UpdateTemplateResponse,
}

/// Response from updating a template.
#[derive(Debug, Clone, Deserialize)]
pub struct UpdateTemplateResponse {
    /// Template ID.
    pub id: u64,
    /// Template name.
    pub name: String,
    /// URL-friendly slug.
    pub slug: String,
    /// Project ID.
    pub project_id: u64,
    /// Folder ID.
    pub folder_id: u64,
    /// Active version number.
    pub active_version: u32,
    /// Extracted merge tags.
    #[serde(default)]
    pub merge_tags: Vec<MergeTag>,
    /// Creation timestamp.
    pub created_at: String,
    /// Last update timestamp.
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
struct GetMergeTagsResponseWrapper {
    #[allow(dead_code)]
    message: String,
    data: MergeTagsList,
}

/// Merge tags for a template version.
#[derive(Debug, Clone, Deserialize)]
pub struct MergeTagsList {
    /// Project ID.
    pub project_id: u64,
    /// Template slug.
    pub template_slug: String,
    /// Template version number.
    pub version: u32,
    /// List of merge tags.
    pub merge_tags: Vec<MergeTag>,
}

/// A merge tag extracted from a template.
#[derive(Debug, Clone, Deserialize)]
pub struct MergeTag {
    /// The merge tag key.
    pub key: String,
    /// Whether this merge tag is required.
    pub required: bool,
    /// The data type of the merge tag (only present for loop children).
    #[serde(rename = "type", default)]
    pub merge_tag_type: Option<String>,
    /// Child merge tags for loop blocks.
    #[serde(default)]
    pub children: Option<Vec<MergeTagChild>>,
}

/// A child merge tag within a loop block.
#[derive(Debug, Clone, Deserialize)]
pub struct MergeTagChild {
    /// The child merge tag key.
    pub key: String,
    /// The data type of the child merge tag.
    #[serde(rename = "type", default)]
    pub merge_tag_type: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GetTemplateHtmlResponseWrapper {
    data: GetTemplateHtmlResponse,
}

/// Response from getting template HTML.
#[derive(Debug, Clone, Deserialize)]
pub struct GetTemplateHtmlResponse {
    /// The template HTML content.
    pub html: String,
    /// Merge tags in the template.
    pub merge_tags: Vec<TemplateHtmlMergeTag>,
    /// The template subject line, if set.
    #[serde(default)]
    pub subject: Option<String>,
}

/// A merge tag from the template HTML endpoint.
#[derive(Debug, Clone, Deserialize)]
pub struct TemplateHtmlMergeTag {
    /// The merge tag key.
    pub key: String,
    /// The merge tag display name.
    pub name: String,
    /// Whether this merge tag is required.
    pub required: bool,
}