-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattachments.py
More file actions
941 lines (711 loc) · 41.5 KB
/
Copy pathattachments.py
File metadata and controls
941 lines (711 loc) · 41.5 KB
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from __future__ import annotations
import httpx
from ..types import SupportedContentType, attachment_create_params
from .._types import Body, Query, Headers, NoneType, NotGiven, not_given
from .._utils import path_template, maybe_transform, async_maybe_transform
from .._compat import cached_property
from .._resource import SyncAPIResource, AsyncAPIResource
from .._response import (
to_raw_response_wrapper,
to_streamed_response_wrapper,
async_to_raw_response_wrapper,
async_to_streamed_response_wrapper,
)
from .._base_client import make_request_options
from ..types.supported_content_type import SupportedContentType
from ..types.attachment_create_response import AttachmentCreateResponse
from ..types.attachment_retrieve_response import AttachmentRetrieveResponse
__all__ = ["AttachmentsResource", "AsyncAttachmentsResource"]
class AttachmentsResource(SyncAPIResource):
"""
Send files (images, videos, documents, audio) with messages by providing a URL in a media part.
Pre-uploading via `POST /v3/attachments` is **optional** and only needed for specific optimization scenarios.
## Sending Media via URL (up to 10MB)
Provide a publicly accessible HTTPS URL with a [supported media type](#supported-file-types) in the `url` field of a media part.
```json
{
"parts": [
{ "type": "media", "url": "https://your-cdn.com/images/photo.jpg" }
]
}
```
This works with any URL you already host — no pre-upload step required. **Maximum file size: 10MB.**
## Pre-Upload (required for files over 10MB)
Use `POST /v3/attachments` when you want to:
- **Send files larger than 10MB** (up to 100MB) — URL-based downloads are limited to 10MB
- **Send the same file to many recipients** — upload once, reuse the `attachment_id` without re-downloading each time
- **Reduce message send latency** — the file is already stored, so sending is faster
**How it works:**
1. `POST /v3/attachments` with file metadata → returns a presigned `upload_url` (valid for **15 minutes**) and a permanent `attachment_id`
2. PUT the raw file bytes to the `upload_url` with the `required_headers` (no JSON or multipart — just the binary content)
3. Reference the `attachment_id` in your media part when sending messages (no expiration)
**Key difference:** When you provide an external `url`, we download and process the file on every send.
When you use a pre-uploaded `attachment_id`, the file is already stored — so repeated sends skip the download step entirely.
## Domain Allowlisting
Attachment URLs in API responses are served from `cdn.linqapp.com`. This includes:
- `url` fields in media and voice memo message parts
- `download_url` fields in attachment and upload response objects
If your application enforces domain allowlists (e.g., for SSRF protection), add:
```
cdn.linqapp.com
```
## Supported File Types
- **Images:** JPEG, PNG, GIF, HEIC, HEIF, TIFF, BMP
- **Videos:** MP4, MOV, M4V
- **Audio:** M4A, AAC, MP3, WAV, AIFF, CAF, AMR
- **Documents:** PDF, TXT, RTF, CSV, Office formats, ZIP
- **Contact & Calendar:** VCF, ICS
## Audio: Attachment vs Voice Memo
Audio files sent as media parts appear as **downloadable file attachments** in iMessage.
To send audio as an **iMessage voice memo bubble** (with native inline playback UI),
use the dedicated `POST /v3/chats/{chatId}/voicememo` endpoint instead.
## File Size Limits
- **URL-based (`url` field):** 10MB maximum
- **Pre-upload (`attachment_id`):** 100MB maximum
## Security & Ownership
Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting.
**What this means for you:**
- An attachment created under your API key can only be referenced by your API key.
- Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else.
- Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted.
- Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations.
Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`.
## Attachment URL Patterns
Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier:
| Tier | URL pattern | TTL |
|---|---|---|
| Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived |
| Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL |
Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client.
## Ephemeral Attachments (Privacy Tier)
For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes:
| Scope | Effect |
|---|---|
| **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. |
| **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. |
**Behavioral differences vs the persistent default:**
| Aspect | Persistent | Ephemeral |
|---|---|---|
| Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL |
| Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours |
| URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry |
| Cross-partner isolation | Enforced | Enforced |
**When to choose ephemeral:**
- Your downstream system processes the file immediately on receipt and does not need to re-read it later.
- You have a compliance requirement that the platform must not retain attachments beyond a short window.
- The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL.
**Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed.
## Deleting an Attachment
To permanently remove an attachment you own, use:
```http
DELETE /v3/attachments/{attachmentId}
Authorization: Bearer <your_api_key>
```
**What this does:**
1. Verifies the attachment is owned by your account. Returns `404` otherwise.
2. Removes the underlying file from Linq storage.
3. Records an audit entry (timestamp, partner, attachment id).
**Response codes:**
| Status | Meaning |
|---|---|
| `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. |
| `400 Bad Request` | `attachmentId` is not a valid UUID. |
| `401 Unauthorized` | Missing or invalid API key. |
| `404 Not Found` | Attachment does not exist or is not owned by your account. |
| `500 Internal Server Error` | Transient infrastructure issue — safe to retry. |
**Effect on message history:**
- Messages that referenced the deleted attachment remain visible.
- The message part that pointed at the attachment is preserved with no attachment reference.
- Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward.
Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete.
## Inbound Media Flow
When one of your phone numbers receives a message with media (image, video, audio, document), the platform:
1. Stores the file under your partner account.
2. Records metadata linked to the inbound message.
3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`.
4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL.
You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL.
## Data Lifecycle Summary
| Data | Persistent tier | Ephemeral tier |
|---|---|---|
| Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` |
| Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes |
| Message body & parts | Retained per message-retention policy | Retained per message-retention policy — unless the line also has **ephemeral messages** enabled (see the Messages page), in which case the message and its parts are deleted 24 hours after creation |
| Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy |
**In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption).
## Compliance Checklist
If you're integrating Linq under a security or privacy review, here is the short list:
- Allowlist exactly one outbound domain: `cdn.linqapp.com`.
- Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact.
- Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow.
- Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day.
- For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response.
- For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design.
"""
@cached_property
def with_raw_response(self) -> AttachmentsResourceWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/linq-team/linq-python#accessing-raw-response-data-eg-headers
"""
return AttachmentsResourceWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> AttachmentsResourceWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/linq-team/linq-python#with_streaming_response
"""
return AttachmentsResourceWithStreamingResponse(self)
def create(
self,
*,
content_type: SupportedContentType,
filename: str,
size_bytes: int,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AttachmentCreateResponse:
"""
**This endpoint is optional.** You can send media by simply providing a URL in
your message's media part — no pre-upload required. Use this endpoint only when
you want to upload a file ahead of time for reuse or latency optimization.
Returns a presigned upload URL and a permanent `attachment_id` you can reference
in future messages.
## Step 1: Request an upload URL
Call this endpoint with file metadata:
```json
POST /v3/attachments
{
"filename": "photo.jpg",
"content_type": "image/jpeg",
"size_bytes": 1024000
}
```
The response includes an `upload_url` (valid for 15 minutes) and a permanent
`attachment_id`.
## Step 2: Upload the file
Make a PUT request to the `upload_url` with the raw file bytes as the request
body. You **must** include all headers from `required_headers` exactly as
returned — the presigned URL is signed with these values and S3 will reject the
upload if they don't match.
The request body is the binary file content — **not** JSON, **not** multipart
form data. The file must equal `size_bytes` bytes (the value you declared in
step 1).
```bash
curl -X PUT "<upload_url from step 1>" \\
-H "Content-Type: image/jpeg" \\
-H "Content-Length: 1024000" \\
--data-binary @photo.jpg
```
## Step 3: Send a message with the attachment
Reference the `attachment_id` in a media part. The ID never expires — use it in
as many messages as you want.
```json
POST /v3/chats
{
"from": "+15559876543",
"to": ["+15551234567"],
"message": {
"parts": [
{ "type": "media", "attachment_id": "<attachment_id from step 1>" }
]
}
}
```
## When to use this instead of a URL in the media part
- Sending the same file to multiple recipients (avoids re-downloading each time)
- Large files where you want to separate upload from message send
- Latency-sensitive sends where the file should already be stored
If you just need to send a file once, skip all of this and pass a `url` directly
in the media part instead.
**File Size Limit:** 100MB
**Unsupported Types:** WebP, SVG, FLAC, OGG, and executable files are explicitly
rejected.
Args:
content_type: Supported MIME types for file attachments and media URLs.
**Images:** image/jpeg, image/png, image/gif, image/heic, image/heif,
image/tiff, image/bmp, image/svg+xml, image/webp, image/x-icon
**Videos:** video/mp4, video/quicktime, video/mpeg, video/mpeg2,
video/x-msvideo, video/3gpp
**Audio:** audio/mpeg, audio/x-m4a, audio/x-caf, audio/x-wav, audio/x-aiff,
audio/aac, audio/midi, audio/amr
**Wallet passes:** application/vnd.apple.pkpass
**Documents:** application/pdf, text/plain, text/markdown, text/vcard, text/rtf,
text/csv, text/html, text/calendar, text/xml, application/json,
application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document,
application/vnd.ms-excel,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
application/vnd.ms-powerpoint,
application/vnd.openxmlformats-officedocument.presentationml.presentation,
application/x-iwork-pages-sffpages, application/x-iwork-numbers-sffnumbers,
application/x-iwork-keynote-sffkey, application/epub+zip, application/zip,
application/x-gzip
**Transcoded on delivery:**
- `audio/x-caf` — CAF files are transcoded to `audio/mp4` for delivery.
**Deprecated (accepted but transcoded):**
- `audio/mp3` — Deprecated. Use `audio/mpeg` instead. Files sent as audio/mp3
will be delivered as audio/mpeg.
- `audio/mp4` — Deprecated. Use `audio/x-m4a` instead. Files sent as audio/mp4
will be delivered as audio/x-m4a.
- `audio/aiff` — Deprecated. Use `audio/x-aiff` instead. Files sent as
audio/aiff will be delivered as audio/x-aiff.
- `image/tiff` — Accepted, but TIFF images are transcoded to JPEG for delivery.
**Unsupported:** FLAC, OGG, and executable files are explicitly rejected.
filename: Name of the file to upload
size_bytes: Size of the file in bytes (max 100MB)
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
return self._post(
"/v3/attachments",
body=maybe_transform(
{
"content_type": content_type,
"filename": filename,
"size_bytes": size_bytes,
},
attachment_create_params.AttachmentCreateParams,
),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=AttachmentCreateResponse,
)
def retrieve(
self,
attachment_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AttachmentRetrieveResponse:
"""
Retrieve metadata for a specific attachment including file information, and URLs
for downloading.
`status`: (**deprecated** — will be removed in a future API version)
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not attachment_id:
raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}")
return self._get(
path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=AttachmentRetrieveResponse,
)
def delete(
self,
attachment_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
Permanently delete an attachment owned by the authenticated partner.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not attachment_id:
raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return self._delete(
path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=NoneType,
)
class AsyncAttachmentsResource(AsyncAPIResource):
"""
Send files (images, videos, documents, audio) with messages by providing a URL in a media part.
Pre-uploading via `POST /v3/attachments` is **optional** and only needed for specific optimization scenarios.
## Sending Media via URL (up to 10MB)
Provide a publicly accessible HTTPS URL with a [supported media type](#supported-file-types) in the `url` field of a media part.
```json
{
"parts": [
{ "type": "media", "url": "https://your-cdn.com/images/photo.jpg" }
]
}
```
This works with any URL you already host — no pre-upload step required. **Maximum file size: 10MB.**
## Pre-Upload (required for files over 10MB)
Use `POST /v3/attachments` when you want to:
- **Send files larger than 10MB** (up to 100MB) — URL-based downloads are limited to 10MB
- **Send the same file to many recipients** — upload once, reuse the `attachment_id` without re-downloading each time
- **Reduce message send latency** — the file is already stored, so sending is faster
**How it works:**
1. `POST /v3/attachments` with file metadata → returns a presigned `upload_url` (valid for **15 minutes**) and a permanent `attachment_id`
2. PUT the raw file bytes to the `upload_url` with the `required_headers` (no JSON or multipart — just the binary content)
3. Reference the `attachment_id` in your media part when sending messages (no expiration)
**Key difference:** When you provide an external `url`, we download and process the file on every send.
When you use a pre-uploaded `attachment_id`, the file is already stored — so repeated sends skip the download step entirely.
## Domain Allowlisting
Attachment URLs in API responses are served from `cdn.linqapp.com`. This includes:
- `url` fields in media and voice memo message parts
- `download_url` fields in attachment and upload response objects
If your application enforces domain allowlists (e.g., for SSRF protection), add:
```
cdn.linqapp.com
```
## Supported File Types
- **Images:** JPEG, PNG, GIF, HEIC, HEIF, TIFF, BMP
- **Videos:** MP4, MOV, M4V
- **Audio:** M4A, AAC, MP3, WAV, AIFF, CAF, AMR
- **Documents:** PDF, TXT, RTF, CSV, Office formats, ZIP
- **Contact & Calendar:** VCF, ICS
## Audio: Attachment vs Voice Memo
Audio files sent as media parts appear as **downloadable file attachments** in iMessage.
To send audio as an **iMessage voice memo bubble** (with native inline playback UI),
use the dedicated `POST /v3/chats/{chatId}/voicememo` endpoint instead.
## File Size Limits
- **URL-based (`url` field):** 10MB maximum
- **Pre-upload (`attachment_id`):** 100MB maximum
## Security & Ownership
Every attachment is bound to the partner account that created or received it. The API enforces ownership on every operation that touches an attachment — sending, retrieving, deleting.
**What this means for you:**
- An attachment created under your API key can only be referenced by your API key.
- Submitting another partner's `attachment_id` returns `404 Not Found`. We do not disclose whether the id exists or belongs to someone else.
- Submitting a CDN URL that resolves to another partner's attachment is rejected before the send is attempted.
- Ownership enforcement applies uniformly across send, create-chat, voice memo, retrieve, and delete operations.
Every attachment-affecting endpoint requires a valid partner API key. Unauthenticated calls return `401 Unauthorized`.
## Attachment URL Patterns
Attachment URLs in API responses and webhook payloads use one of two layouts, depending on the attachment's tier:
| Tier | URL pattern | TTL |
|---|---|---|
| Persistent (default) | `https://cdn.linqapp.com/attachments/partners/{partner_id}/{attachment_id}/{filename}` | Long-lived |
| Ephemeral | Pre-signed URL pointing at the ephemeral prefix on `cdn.linqapp.com` | 15 minutes per signed URL — re-fetch via the API for a fresh URL |
Inbound media you receive over webhooks uses the same layout your outbound sends produce, so the URL you store and the URL you build look identical — no special casing in your client.
## Ephemeral Attachments (Privacy Tier)
For regulated or sensitive content, opt in to the **ephemeral attachments** tier by contacting your Linq support contact. You can request it at two scopes:
| Scope | Effect |
|---|---|
| **Partner-wide** | Every outbound and inbound attachment on every phone number under your account is routed through the ephemeral tier. |
| **Per phone number** | Only the specified phone numbers route their attachments through the ephemeral tier. The rest stay on the persistent tier. |
**Behavioral differences vs the persistent default:**
| Aspect | Persistent | Ephemeral |
|---|---|---|
| Download URL form | Long-lived CDN URL | Pre-signed URL with short TTL |
| Retention floor | Indefinite (until you call `DELETE`) | **Hard backstop: 1 day** — even without an explicit `DELETE`, the platform removes the underlying bytes after 24 hours |
| URL re-fetch | Not required | Fetch via `GET /v3/attachments/{attachmentId}` for a fresh signed URL after TTL expiry |
| Cross-partner isolation | Enforced | Enforced |
**When to choose ephemeral:**
- Your downstream system processes the file immediately on receipt and does not need to re-read it later.
- You have a compliance requirement that the platform must not retain attachments beyond a short window.
- The content is high-sensitivity (PHI, financial documents, identity verification) and you do not want it sitting behind a long-lived URL.
**Important:** ephemeral applies in *both directions* — outbound files you upload **and** inbound media received by the phone numbers in that scope. Download bytes you need to keep promptly, or fetch a fresh signed URL via the API when needed.
## Deleting an Attachment
To permanently remove an attachment you own, use:
```http
DELETE /v3/attachments/{attachmentId}
Authorization: Bearer <your_api_key>
```
**What this does:**
1. Verifies the attachment is owned by your account. Returns `404` otherwise.
2. Removes the underlying file from Linq storage.
3. Records an audit entry (timestamp, partner, attachment id).
**Response codes:**
| Status | Meaning |
|---|---|
| `204 No Content` | Deletion succeeded. The attachment is removed from Linq storage. |
| `400 Bad Request` | `attachmentId` is not a valid UUID. |
| `401 Unauthorized` | Missing or invalid API key. |
| `404 Not Found` | Attachment does not exist or is not owned by your account. |
| `500 Internal Server Error` | Transient infrastructure issue — safe to retry. |
**Effect on message history:**
- Messages that referenced the deleted attachment remain visible.
- The message part that pointed at the attachment is preserved with no attachment reference.
- Webhook payloads previously delivered to you retain the original URL string, but downloads from that URL return `404` going forward.
Deletion is **irreversible**. Once `204` is returned, the bytes are gone — there is no undelete.
## Inbound Media Flow
When one of your phone numbers receives a message with media (image, video, audio, document), the platform:
1. Stores the file under your partner account.
2. Records metadata linked to the inbound message.
3. Delivers a webhook whose `parts[]` array includes a `media` part with a `url` pointing at `cdn.linqapp.com`.
4. If the receiving phone is opted in to ephemeral, the `url` is a short-TTL signed URL.
You can acknowledge the webhook without fetching the file inline, and lazy-load via `GET /v3/attachments/{attachmentId}` later. For ephemeral attachments, retrieving via the API always returns a freshly-signed URL.
## Data Lifecycle Summary
| Data | Persistent tier | Ephemeral tier |
|---|---|---|
| Attachment bytes | Retained until you `DELETE` | **Auto-removed after 1 day**, also removable via `DELETE` |
| Attachment metadata (id, filename, mime type, size) | Retained until you `DELETE` | Removed alongside the bytes |
| Message body & parts | Retained per message-retention policy | Retained per message-retention policy — unless the line also has **ephemeral messages** enabled (see the Messages page), in which case the message and its parts are deleted 24 hours after creation |
| Audit log of deletions | Retained per platform retention policy | Retained per platform retention policy |
**In transit:** TLS 1.2+ everywhere. **At rest:** AES-256 (server-side encryption).
## Compliance Checklist
If you're integrating Linq under a security or privacy review, here is the short list:
- Allowlist exactly one outbound domain: `cdn.linqapp.com`.
- Decide whether you need ephemeral attachments (high-sensitivity content) — request enablement through your Linq support contact.
- Implement `DELETE /v3/attachments/{attachmentId}` calls in your deletion workflow.
- Persist any attachments your application needs long-term — Linq is the authoritative source until you delete, but the ephemeral tier auto-purges after 1 day.
- For audit: every deletion is logged on Linq's side. Surface a confirmation in your application UI based on the `204` response.
- For end-user "right to delete" requests: enumerate attachment ids and `DELETE` each. The platform does not provide a partner-wide wipe endpoint — deletion is per-attachment by design.
"""
@cached_property
def with_raw_response(self) -> AsyncAttachmentsResourceWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/linq-team/linq-python#accessing-raw-response-data-eg-headers
"""
return AsyncAttachmentsResourceWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> AsyncAttachmentsResourceWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/linq-team/linq-python#with_streaming_response
"""
return AsyncAttachmentsResourceWithStreamingResponse(self)
async def create(
self,
*,
content_type: SupportedContentType,
filename: str,
size_bytes: int,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AttachmentCreateResponse:
"""
**This endpoint is optional.** You can send media by simply providing a URL in
your message's media part — no pre-upload required. Use this endpoint only when
you want to upload a file ahead of time for reuse or latency optimization.
Returns a presigned upload URL and a permanent `attachment_id` you can reference
in future messages.
## Step 1: Request an upload URL
Call this endpoint with file metadata:
```json
POST /v3/attachments
{
"filename": "photo.jpg",
"content_type": "image/jpeg",
"size_bytes": 1024000
}
```
The response includes an `upload_url` (valid for 15 minutes) and a permanent
`attachment_id`.
## Step 2: Upload the file
Make a PUT request to the `upload_url` with the raw file bytes as the request
body. You **must** include all headers from `required_headers` exactly as
returned — the presigned URL is signed with these values and S3 will reject the
upload if they don't match.
The request body is the binary file content — **not** JSON, **not** multipart
form data. The file must equal `size_bytes` bytes (the value you declared in
step 1).
```bash
curl -X PUT "<upload_url from step 1>" \\
-H "Content-Type: image/jpeg" \\
-H "Content-Length: 1024000" \\
--data-binary @photo.jpg
```
## Step 3: Send a message with the attachment
Reference the `attachment_id` in a media part. The ID never expires — use it in
as many messages as you want.
```json
POST /v3/chats
{
"from": "+15559876543",
"to": ["+15551234567"],
"message": {
"parts": [
{ "type": "media", "attachment_id": "<attachment_id from step 1>" }
]
}
}
```
## When to use this instead of a URL in the media part
- Sending the same file to multiple recipients (avoids re-downloading each time)
- Large files where you want to separate upload from message send
- Latency-sensitive sends where the file should already be stored
If you just need to send a file once, skip all of this and pass a `url` directly
in the media part instead.
**File Size Limit:** 100MB
**Unsupported Types:** WebP, SVG, FLAC, OGG, and executable files are explicitly
rejected.
Args:
content_type: Supported MIME types for file attachments and media URLs.
**Images:** image/jpeg, image/png, image/gif, image/heic, image/heif,
image/tiff, image/bmp, image/svg+xml, image/webp, image/x-icon
**Videos:** video/mp4, video/quicktime, video/mpeg, video/mpeg2,
video/x-msvideo, video/3gpp
**Audio:** audio/mpeg, audio/x-m4a, audio/x-caf, audio/x-wav, audio/x-aiff,
audio/aac, audio/midi, audio/amr
**Wallet passes:** application/vnd.apple.pkpass
**Documents:** application/pdf, text/plain, text/markdown, text/vcard, text/rtf,
text/csv, text/html, text/calendar, text/xml, application/json,
application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document,
application/vnd.ms-excel,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
application/vnd.ms-powerpoint,
application/vnd.openxmlformats-officedocument.presentationml.presentation,
application/x-iwork-pages-sffpages, application/x-iwork-numbers-sffnumbers,
application/x-iwork-keynote-sffkey, application/epub+zip, application/zip,
application/x-gzip
**Transcoded on delivery:**
- `audio/x-caf` — CAF files are transcoded to `audio/mp4` for delivery.
**Deprecated (accepted but transcoded):**
- `audio/mp3` — Deprecated. Use `audio/mpeg` instead. Files sent as audio/mp3
will be delivered as audio/mpeg.
- `audio/mp4` — Deprecated. Use `audio/x-m4a` instead. Files sent as audio/mp4
will be delivered as audio/x-m4a.
- `audio/aiff` — Deprecated. Use `audio/x-aiff` instead. Files sent as
audio/aiff will be delivered as audio/x-aiff.
- `image/tiff` — Accepted, but TIFF images are transcoded to JPEG for delivery.
**Unsupported:** FLAC, OGG, and executable files are explicitly rejected.
filename: Name of the file to upload
size_bytes: Size of the file in bytes (max 100MB)
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
return await self._post(
"/v3/attachments",
body=await async_maybe_transform(
{
"content_type": content_type,
"filename": filename,
"size_bytes": size_bytes,
},
attachment_create_params.AttachmentCreateParams,
),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=AttachmentCreateResponse,
)
async def retrieve(
self,
attachment_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AttachmentRetrieveResponse:
"""
Retrieve metadata for a specific attachment including file information, and URLs
for downloading.
`status`: (**deprecated** — will be removed in a future API version)
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not attachment_id:
raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}")
return await self._get(
path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=AttachmentRetrieveResponse,
)
async def delete(
self,
attachment_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
Permanently delete an attachment owned by the authenticated partner.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not attachment_id:
raise ValueError(f"Expected a non-empty value for `attachment_id` but received {attachment_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
path_template("/v3/attachments/{attachment_id}", attachment_id=attachment_id),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=NoneType,
)
class AttachmentsResourceWithRawResponse:
def __init__(self, attachments: AttachmentsResource) -> None:
self._attachments = attachments
self.create = to_raw_response_wrapper(
attachments.create,
)
self.retrieve = to_raw_response_wrapper(
attachments.retrieve,
)
self.delete = to_raw_response_wrapper(
attachments.delete,
)
class AsyncAttachmentsResourceWithRawResponse:
def __init__(self, attachments: AsyncAttachmentsResource) -> None:
self._attachments = attachments
self.create = async_to_raw_response_wrapper(
attachments.create,
)
self.retrieve = async_to_raw_response_wrapper(
attachments.retrieve,
)
self.delete = async_to_raw_response_wrapper(
attachments.delete,
)
class AttachmentsResourceWithStreamingResponse:
def __init__(self, attachments: AttachmentsResource) -> None:
self._attachments = attachments
self.create = to_streamed_response_wrapper(
attachments.create,
)
self.retrieve = to_streamed_response_wrapper(
attachments.retrieve,
)
self.delete = to_streamed_response_wrapper(
attachments.delete,
)
class AsyncAttachmentsResourceWithStreamingResponse:
def __init__(self, attachments: AsyncAttachmentsResource) -> None:
self._attachments = attachments
self.create = async_to_streamed_response_wrapper(
attachments.create,
)
self.retrieve = async_to_streamed_response_wrapper(
attachments.retrieve,
)
self.delete = async_to_streamed_response_wrapper(
attachments.delete,
)