or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

account-management.mdasync-api.mdfile-upload.mdhtml-utilities.mdindex.mdlow-level-api.mdpage-operations.md

async-api.mddocs/

0

# Asynchronous API

1

2

Complete async/await interface for Telegraph operations using `httpx` for HTTP requests. All synchronous methods have async counterparts with identical signatures and functionality.

3

4

## Installation

5

6

```bash

7

pip install 'telegraph[aio]'

8

```

9

10

This installs the `httpx` dependency required for async operations.

11

12

## Import and Setup

13

14

```python

15

from telegraph.aio import Telegraph

16

import asyncio

17

18

# Create async Telegraph client

19

telegraph = Telegraph(access_token='your_token')

20

```

21

22

## Capabilities

23

24

### Account Management (Async)

25

26

All account operations with async/await support.

27

28

```python { .api }

29

async def create_account(short_name: str, author_name: str = None, author_url: str = None, replace_token: bool = True) -> dict:

30

"""

31

Create a new Telegraph account (async).

32

33

Parameters and returns identical to synchronous version.

34

"""

35

36

async def edit_account_info(short_name: str = None, author_name: str = None, author_url: str = None) -> dict:

37

"""

38

Update Telegraph account information (async).

39

"""

40

41

async def get_account_info(fields: list = None) -> dict:

42

"""

43

Get Telegraph account information (async).

44

"""

45

46

async def revoke_access_token() -> dict:

47

"""

48

Revoke current access token and generate new one (async).

49

"""

50

```

51

52

Usage example:

53

54

```python

55

import asyncio

56

from telegraph.aio import Telegraph

57

58

async def setup_account():

59

telegraph = Telegraph()

60

61

# Create account

62

response = await telegraph.create_account(

63

short_name='async-blog',

64

author_name='Async Author'

65

)

66

67

# Get account info

68

info = await telegraph.get_account_info()

69

print(f"Account: {info['short_name']}")

70

71

return telegraph

72

73

# Run async function

74

telegraph = asyncio.run(setup_account())

75

```

76

77

### Page Operations (Async)

78

79

All page management operations with async support.

80

81

```python { .api }

82

async def create_page(title: str, content: list = None, html_content: str = None, author_name: str = None, author_url: str = None, return_content: bool = False) -> dict:

83

"""

84

Create a new Telegraph page (async).

85

"""

86

87

async def edit_page(path: str, title: str, content: list = None, html_content: str = None, author_name: str = None, author_url: str = None, return_content: bool = False) -> dict:

88

"""

89

Edit an existing Telegraph page (async).

90

"""

91

92

async def get_page(path: str, return_content: bool = True, return_html: bool = True) -> dict:

93

"""

94

Get a Telegraph page (async).

95

"""

96

97

async def get_page_list(offset: int = 0, limit: int = 50) -> dict:

98

"""

99

Get list of account pages (async).

100

"""

101

102

async def get_views(path: str, year: int = None, month: int = None, day: int = None, hour: int = None) -> dict:

103

"""

104

Get page view statistics (async).

105

"""

106

```

107

108

Usage example:

109

110

```python

111

async def manage_pages():

112

telegraph = Telegraph(access_token='your_token')

113

114

# Create multiple pages concurrently

115

tasks = []

116

for i in range(3):

117

task = telegraph.create_page(

118

title=f'Async Page {i+1}',

119

html_content=f'<p>This is page {i+1} created asynchronously.</p>'

120

)

121

tasks.append(task)

122

123

# Wait for all pages to be created

124

results = await asyncio.gather(*tasks)

125

126

# Print URLs

127

for result in results:

128

print(f"Created: {result['url']}")

129

130

# Get page list

131

page_list = await telegraph.get_page_list()

132

print(f"Total pages: {page_list['total_count']}")

133

134

asyncio.run(manage_pages())

135

```

136

137

### File Upload (Async)

138

139

Asynchronous file upload functionality.

140

141

```python { .api }

142

async def upload_file(f) -> list:

143

"""

144

Upload file to Telegraph servers (async, unofficial API).

145

146

Parameters and returns identical to synchronous version.

147

"""

148

```

149

150

Usage example:

151

152

```python

153

async def upload_and_create():

154

telegraph = Telegraph()

155

156

# Upload file

157

result = await telegraph.upload_file('image.jpg')

158

image_src = result[0]['src']

159

160

# Create page with uploaded image

161

response = await telegraph.create_page(

162

title='Async Upload Example',

163

html_content=f'<img src="{image_src}" alt="Async uploaded image">'

164

)

165

166

print(f"Page with image: {response['url']}")

167

168

asyncio.run(upload_and_create())

169

```

170

171

## Async Context Management

172

173

For better connection management, consider using the async context manager pattern:

174

175

```python

176

import asyncio

177

from telegraph.aio import Telegraph

178

179

async def main():

180

telegraph = Telegraph()

181

182

try:

183

# Perform operations

184

await telegraph.create_account(short_name='context-example')

185

186

response = await telegraph.create_page(

187

title='Context Example',

188

html_content='<p>Using proper async context management.</p>'

189

)

190

191

print(f"Page created: {response['url']}")

192

193

finally:

194

# Close the HTTP client session

195

await telegraph._telegraph.session.aclose()

196

197

asyncio.run(main())

198

```

199

200

## Concurrent Operations

201

202

Take advantage of async capabilities for concurrent operations:

203

204

```python

205

async def concurrent_example():

206

telegraph = Telegraph(access_token='your_token')

207

208

# Perform multiple operations concurrently

209

account_task = telegraph.get_account_info()

210

pages_task = telegraph.get_page_list(limit=5)

211

212

# Wait for both to complete

213

account_info, page_list = await asyncio.gather(account_task, pages_task)

214

215

print(f"Account: {account_info['short_name']}")

216

print(f"Pages: {page_list['total_count']}")

217

218

# Process pages concurrently

219

view_tasks = []

220

for page in page_list['pages']:

221

task = telegraph.get_views(page['path'])

222

view_tasks.append(task)

223

224

view_results = await asyncio.gather(*view_tasks)

225

226

for page, views in zip(page_list['pages'], view_results):

227

print(f"{page['title']}: {views['views']} views")

228

229

asyncio.run(concurrent_example())

230

```

231

232

## Error Handling

233

234

Async operations raise the same exceptions as synchronous versions:

235

236

```python

237

from telegraph.aio import Telegraph

238

from telegraph.exceptions import TelegraphException, RetryAfterError

239

240

async def error_handling_example():

241

telegraph = Telegraph()

242

243

try:

244

response = await telegraph.create_account(short_name='test')

245

except RetryAfterError as e:

246

print(f"Rate limited. Retry after {e.retry_after} seconds")

247

await asyncio.sleep(e.retry_after)

248

# Retry operation

249

response = await telegraph.create_account(short_name='test')

250

except TelegraphException as e:

251

print(f"API error: {e}")

252

253

asyncio.run(error_handling_example())

254

```

255

256

## Migration from Sync

257

258

Converting synchronous code to async is straightforward:

259

260

```python

261

# Synchronous version

262

from telegraph import Telegraph

263

264

telegraph = Telegraph()

265

response = telegraph.create_account(short_name='sync-example')

266

page = telegraph.create_page(title='Sync Page', html_content='<p>Sync content</p>')

267

268

# Asynchronous version

269

from telegraph.aio import Telegraph

270

import asyncio

271

272

async def async_version():

273

telegraph = Telegraph()

274

response = await telegraph.create_account(short_name='async-example')

275

page = await telegraph.create_page(title='Async Page', html_content='<p>Async content</p>')

276

277

asyncio.run(async_version())

278

```

279

280

## Performance Benefits

281

282

Async API provides significant performance benefits for:

283

284

- **Batch operations**: Creating multiple pages or accounts

285

- **High-concurrency applications**: Web servers handling many requests

286

- **I/O-bound workflows**: Operations waiting on network responses

287

- **Integration scenarios**: Telegraph operations alongside other async APIs

288

289

Use the async API when you need non-blocking operations or are already working in an async Python environment.