1
+ """
2
+ JSON Payload Usage Examples for Twilio Python SDK
3
+
4
+ This example demonstrates how to use JSON payloads with Twilio APIs.
5
+ Since version 9.0.0, the Twilio Python SDK supports application/json content type.
6
+ """
7
+
8
+ import os
9
+ import json
10
+ from twilio .rest import Client
11
+ from twilio .http .http_client import TwilioHttpClient
12
+
13
+
14
+ # Your Account SID and Auth Token from console.twilio.com
15
+ ACCOUNT_SID = os .environ .get ("TWILIO_ACCOUNT_SID" , "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" )
16
+ AUTH_TOKEN = os .environ .get ("TWILIO_AUTH_TOKEN" , "your_auth_token" )
17
+
18
+
19
+ def example_json_with_custom_request ():
20
+ """
21
+ Example: Using JSON payload with custom HTTP requests
22
+
23
+ This shows how to make direct API calls with JSON payloads using
24
+ the underlying HTTP client when you need more control.
25
+ """
26
+ print ("=== JSON Payload with Custom HTTP Client ===" )
27
+
28
+ client = Client (ACCOUNT_SID , AUTH_TOKEN )
29
+
30
+ # Example: Custom API call with JSON payload
31
+ # This is useful for beta APIs or special endpoints that require JSON
32
+ json_payload = {
33
+ "message" : "Hello World" ,
34
+ "priority" : "high" ,
35
+ "metadata" : {
36
+ "source" : "python_sdk" ,
37
+ "version" : "9.0.0"
38
+ }
39
+ }
40
+
41
+ headers = {
42
+ "Content-Type" : "application/json" ,
43
+ "Accept" : "application/json"
44
+ }
45
+
46
+ # Note: This is a demonstration - replace with actual Twilio API endpoint
47
+ url = f"https://api.twilio.com/2010-04-01/Accounts/{ ACCOUNT_SID } /CustomResource.json"
48
+
49
+ print (f"JSON Payload: { json .dumps (json_payload , indent = 2 )} " )
50
+ print (f"Headers: { headers } " )
51
+ print (f"URL: { url } " )
52
+
53
+ # Uncomment below to make actual request (requires valid endpoint):
54
+ # try:
55
+ # response = client.http_client.request(
56
+ # method="POST",
57
+ # url=url,
58
+ # data=json_payload,
59
+ # headers=headers
60
+ # )
61
+ # print(f"Response: {response.status_code} - {response.text}")
62
+ # except Exception as e:
63
+ # print(f"Request failed: {e}")
64
+
65
+
66
+ def example_conversations_api_json ():
67
+ """
68
+ Example: Using JSON with Conversations API
69
+
70
+ Some Twilio APIs, like Conversations, may benefit from JSON payloads
71
+ for complex data structures.
72
+ """
73
+ print ("\n === JSON Payload with Conversations API ===" )
74
+
75
+ client = Client (ACCOUNT_SID , AUTH_TOKEN )
76
+
77
+ # Example: Creating a conversation with JSON metadata
78
+ conversation_data = {
79
+ "friendly_name" : "Customer Support Chat" ,
80
+ "attributes" : json .dumps ({
81
+ "customer_id" : "12345" ,
82
+ "department" : "technical_support" ,
83
+ "priority" : "high" ,
84
+ "tags" : ["bug_report" , "urgent" ]
85
+ })
86
+ }
87
+
88
+ print (f"Conversation data: { json .dumps (conversation_data , indent = 2 )} " )
89
+
90
+ # Uncomment to create actual conversation:
91
+ # try:
92
+ # conversation = client.conversations.v1.conversations.create(
93
+ # friendly_name=conversation_data["friendly_name"],
94
+ # attributes=conversation_data["attributes"]
95
+ # )
96
+ # print(f"Created conversation: {conversation.sid}")
97
+ # except Exception as e:
98
+ # print(f"Failed to create conversation: {e}")
99
+
100
+
101
+ def example_webhook_with_json ():
102
+ """
103
+ Example: Webhook configuration with JSON payload
104
+
105
+ Shows how to configure webhooks that expect JSON responses.
106
+ """
107
+ print ("\n === Webhook Configuration with JSON ===" )
108
+
109
+ # Example webhook URL that expects JSON
110
+ webhook_url = "https://your-app.example.com/webhook"
111
+
112
+ # JSON payload for webhook configuration
113
+ webhook_config = {
114
+ "url" : webhook_url ,
115
+ "method" : "POST" ,
116
+ "content_type" : "application/json" ,
117
+ "events" : ["message-added" , "participant-joined" ]
118
+ }
119
+
120
+ print (f"Webhook configuration: { json .dumps (webhook_config , indent = 2 )} " )
121
+
122
+ # This would be used when configuring services that support JSON webhooks
123
+ print ("Use this configuration when setting up webhooks that need JSON format" )
124
+
125
+
126
+ def example_bulk_operations_json ():
127
+ """
128
+ Example: Bulk operations with JSON payload
129
+
130
+ Demonstrates how JSON payloads can be useful for bulk operations
131
+ or complex data structures.
132
+ """
133
+ print ("\n === Bulk Operations with JSON ===" )
134
+
135
+ # Example: Bulk message data
136
+ bulk_messages = {
137
+ "messages" : [
138
+ {
139
+ "to" : "+1234567890" ,
140
+ "body" : "Hello Alice!" ,
141
+ "metadata" : {"customer_id" : "001" }
142
+ },
143
+ {
144
+ "to" : "+1987654321" ,
145
+ "body" : "Hello Bob!" ,
146
+ "metadata" : {"customer_id" : "002" }
147
+ }
148
+ ],
149
+ "options" : {
150
+ "send_at" : "2024-01-01T12:00:00Z" ,
151
+ "callback_url" : "https://example.com/status"
152
+ }
153
+ }
154
+
155
+ print (f"Bulk operation payload: { json .dumps (bulk_messages , indent = 2 )} " )
156
+
157
+ # For actual bulk operations, you would typically iterate:
158
+ client = Client (ACCOUNT_SID , AUTH_TOKEN )
159
+
160
+ print ("\n Processing messages individually:" )
161
+ for msg_data in bulk_messages ["messages" ]:
162
+ print (f"Would send: { msg_data ['body' ]} to { msg_data ['to' ]} " )
163
+ # Uncomment to send actual messages:
164
+ # try:
165
+ # message = client.messages.create(
166
+ # to=msg_data["to"],
167
+ # from_="+1234567890", # Your Twilio number
168
+ # body=msg_data["body"]
169
+ # )
170
+ # print(f"Sent message: {message.sid}")
171
+ # except Exception as e:
172
+ # print(f"Failed to send message: {e}")
173
+
174
+
175
+ async def example_async_json_requests ():
176
+ """
177
+ Example: Asynchronous requests with JSON payload
178
+
179
+ Shows how to use JSON payloads with async HTTP client.
180
+ """
181
+ print ("\n === Async JSON Requests ===" )
182
+
183
+ from twilio .http .async_http_client import AsyncTwilioHttpClient
184
+
185
+ async_client = Client (
186
+ ACCOUNT_SID ,
187
+ AUTH_TOKEN ,
188
+ http_client = AsyncTwilioHttpClient ()
189
+ )
190
+
191
+ # Example async operation with JSON
192
+ json_data = {
193
+ "async_operation" : True ,
194
+ "data" : {
195
+ "priority" : "high" ,
196
+ "process_immediately" : True
197
+ }
198
+ }
199
+
200
+ print (f"Async JSON payload: { json .dumps (json_data , indent = 2 )} " )
201
+
202
+ # Uncomment for actual async operations:
203
+ # try:
204
+ # # Example: async message creation
205
+ # message = await async_client.messages.create_async(
206
+ # to="+1234567890",
207
+ # from_="+1987654321",
208
+ # body="Async message with JSON context"
209
+ # )
210
+ # print(f"Async message sent: {message.sid}")
211
+ # except Exception as e:
212
+ # print(f"Async operation failed: {e}")
213
+
214
+
215
+ def example_api_versioning_with_json ():
216
+ """
217
+ Example: API versioning and JSON content negotiation
218
+
219
+ Shows how to work with different API versions that may require JSON.
220
+ """
221
+ print ("\n === API Versioning with JSON ===" )
222
+
223
+ client = Client (ACCOUNT_SID , AUTH_TOKEN )
224
+
225
+ # Example: Using specific API version with JSON
226
+ headers = {
227
+ "Content-Type" : "application/json" ,
228
+ "Accept" : "application/json" ,
229
+ "Twilio-API-Version" : "2010-04-01" # Specify API version
230
+ }
231
+
232
+ api_request = {
233
+ "version" : "2010-04-01" ,
234
+ "features" : ["json_support" , "bulk_operations" ],
235
+ "client_info" : {
236
+ "sdk" : "twilio-python" ,
237
+ "version" : "9.0.0+" ,
238
+ "language" : "python"
239
+ }
240
+ }
241
+
242
+ print (f"API request with versioning: { json .dumps (api_request , indent = 2 )} " )
243
+ print (f"Headers: { json .dumps (headers , indent = 2 )} " )
244
+
245
+
246
+ def main ():
247
+ """
248
+ Run all JSON usage examples
249
+ """
250
+ print ("Twilio Python SDK - JSON Payload Usage Examples" )
251
+ print ("=" * 50 )
252
+ print ()
253
+ print ("Note: These examples demonstrate JSON payload usage patterns." )
254
+ print ("Uncomment the actual API calls to test with your Twilio account." )
255
+ print ()
256
+
257
+ # Run all examples
258
+ example_json_with_custom_request ()
259
+ example_conversations_api_json ()
260
+ example_webhook_with_json ()
261
+ example_bulk_operations_json ()
262
+
263
+ # Note: async example would need to be run in async context
264
+ print ("\n === Async Example (requires async context) ===" )
265
+ print ("To run async examples, use: asyncio.run(example_async_json_requests())" )
266
+
267
+ example_api_versioning_with_json ()
268
+
269
+ print ("\n " + "=" * 50 )
270
+ print ("JSON Examples Complete!" )
271
+ print ()
272
+ print ("Key points:" )
273
+ print ("- Set Content-Type header to 'application/json' for JSON payloads" )
274
+ print ("- Use json.dumps() to serialize Python dicts to JSON strings when needed" )
275
+ print ("- The SDK automatically handles JSON when the correct headers are set" )
276
+ print ("- JSON is useful for complex data, bulk operations, and modern APIs" )
277
+
278
+
279
+ if __name__ == "__main__" :
280
+ main ()
0 commit comments