Skip to content

Commit e549a5f

Browse files
Merge pull request #8 from tiwarishubham635/copilot/fix-1
Add comprehensive JSON payload documentation and examples
2 parents 75127db + 0c1fd9f commit e549a5f

File tree

3 files changed

+324
-0
lines changed

3 files changed

+324
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,9 +305,45 @@ print(str(r))
305305
<Response><Say>Welcome to twilio!</Say></Response>
306306
```
307307

308+
### Using JSON Payloads
309+
310+
Since version 9.0.0, the Twilio Python SDK supports sending JSON payloads for API requests. This is useful for APIs that accept complex data structures or when you need more control over request formatting.
311+
312+
```python
313+
from twilio.rest import Client
314+
import json
315+
316+
client = Client(account_sid, auth_token)
317+
318+
# Example: Custom API request with JSON payload
319+
json_payload = {
320+
"message": "Hello World",
321+
"metadata": {
322+
"source": "python_sdk",
323+
"priority": "high"
324+
}
325+
}
326+
327+
headers = {
328+
"Content-Type": "application/json",
329+
"Accept": "application/json"
330+
}
331+
332+
# The SDK automatically handles JSON when Content-Type is application/json
333+
response = client.http_client.request(
334+
method="POST",
335+
url="https://api.twilio.com/your-endpoint",
336+
data=json_payload,
337+
headers=headers
338+
)
339+
```
340+
341+
For comprehensive examples of JSON payload usage, see [examples/json_usage.py](./examples/json_usage.py).
342+
308343
### Other advanced examples
309344

310345
- [Learn how to create your own custom HTTP client](./advanced-examples/custom-http-client.md)
346+
- [JSON payload usage examples](./examples/json_usage.py)
311347

312348
### Docker Image
313349

examples/basic_usage.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ def example():
4040
twiml_xml = twiml_response.to_xml()
4141
print("Generated twiml: {}".format(twiml_xml))
4242

43+
# JSON payload example (since v9.0.0)
44+
print("JSON payload example...")
45+
json_data = {"message": "Hello", "priority": "high"}
46+
headers = {"Content-Type": "application/json", "Accept": "application/json"}
47+
print("JSON payload: {}".format(json_data))
48+
print("Use headers: {}".format(headers))
49+
print("See examples/json_usage.py for complete JSON examples")
50+
4351

4452
if __name__ == "__main__":
4553
example()

examples/json_usage.py

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
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("\nProcessing 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

Comments
 (0)