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

low-level-api.mddocs/

0

# Low-level API

1

2

Direct Telegraph API access for advanced use cases, custom implementations, and fine-grained control over API requests. The low-level API provides minimal abstraction over the Telegraph REST API.

3

4

## Capabilities

5

6

### TelegraphApi Class

7

8

Low-level Telegraph API client for direct API method calls.

9

10

```python { .api }

11

class TelegraphApi:

12

"""

13

Low-level Telegraph API client.

14

15

Parameters:

16

- access_token (str, optional): Telegraph access token for authenticated requests

17

- domain (str): Telegraph domain, defaults to 'telegra.ph'

18

"""

19

def __init__(self, access_token: str = None, domain: str = 'telegra.ph'):

20

pass

21

```

22

23

Usage example:

24

25

```python

26

from telegraph.api import TelegraphApi

27

28

# Create low-level API client

29

api = TelegraphApi(access_token='your_token')

30

31

# Alternative domain

32

api = TelegraphApi(domain='graph.org')

33

```

34

35

### Direct API Method Calls

36

37

Make direct calls to Telegraph API endpoints with custom parameters.

38

39

```python { .api }

40

def method(self, method: str, values: dict = None, path: str = '') -> dict:

41

"""

42

Make direct Telegraph API method call.

43

44

Parameters:

45

- method (str): Telegraph API method name (e.g., 'createPage', 'getPage')

46

- values (dict, optional): Method parameters as key-value pairs

47

- path (str, optional): Additional path component for methods like getPage

48

49

Returns:

50

dict: API response data

51

52

Raises:

53

TelegraphException: API error occurred

54

RetryAfterError: Rate limiting with retry timing

55

"""

56

```

57

58

Usage examples:

59

60

```python

61

from telegraph.api import TelegraphApi

62

from telegraph.exceptions import TelegraphException, RetryAfterError

63

64

api = TelegraphApi()

65

66

# Create account using low-level API

67

try:

68

response = api.method('createAccount', {

69

'short_name': 'test-account',

70

'author_name': 'Test Author',

71

'author_url': 'https://example.com'

72

})

73

access_token = response['access_token']

74

print(f"Account created: {access_token}")

75

except RetryAfterError as e:

76

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

77

except TelegraphException as e:

78

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

79

80

# Get page using path parameter

81

api = TelegraphApi(access_token=access_token)

82

page_data = api.method('getPage', path='My-Page-12-31', values={

83

'return_content': True

84

})

85

86

# Get account info with custom fields

87

account_info = api.method('getAccountInfo', {

88

'fields': '["short_name", "author_name", "page_count"]'

89

})

90

```

91

92

### Low-level File Upload

93

94

Direct file upload using the unofficial Telegraph upload endpoint.

95

96

```python { .api }

97

def upload_file(self, f) -> list:

98

"""

99

Upload file using low-level API (unofficial).

100

101

Parameters and behavior identical to high-level Telegraph.upload_file()

102

"""

103

```

104

105

Usage example:

106

107

```python

108

api = TelegraphApi()

109

result = api.upload_file('image.jpg')

110

file_url = result[0]['src']

111

print(f"Uploaded to: https://telegra.ph{file_url}")

112

```

113

114

## Advanced Usage Patterns

115

116

### Custom Domain Support

117

118

Use Telegraph mirrors or custom domains:

119

120

```python

121

# Use alternative domain

122

api = TelegraphApi(domain='graph.org')

123

124

# Create account on alternative domain

125

response = api.method('createAccount', {

126

'short_name': 'mirror-account'

127

})

128

```

129

130

### Raw API Response Handling

131

132

Process raw Telegraph API responses without high-level abstractions:

133

134

```python

135

def create_page_raw(api, title, content_json):

136

"""Create page with raw content JSON."""

137

response = api.method('createPage', {

138

'title': title,

139

'content': content_json,

140

'return_content': True

141

})

142

return response

143

144

# Use with pre-serialized content

145

import json

146

content_json = json.dumps([

147

{'tag': 'p', 'children': ['Raw content']}

148

], separators=(',', ':'), ensure_ascii=False)

149

150

api = TelegraphApi(access_token='your_token')

151

result = create_page_raw(api, 'Raw Page', content_json)

152

```

153

154

### Custom Error Handling

155

156

Implement custom retry logic and error handling:

157

158

```python

159

import time

160

from telegraph.api import TelegraphApi

161

from telegraph.exceptions import RetryAfterError, TelegraphException

162

163

def api_call_with_retry(api, method, values=None, path='', max_retries=3):

164

"""Make API call with automatic retry on rate limiting."""

165

for attempt in range(max_retries):

166

try:

167

return api.method(method, values, path)

168

except RetryAfterError as e:

169

if attempt == max_retries - 1:

170

raise # Re-raise on final attempt

171

print(f"Rate limited, waiting {e.retry_after} seconds...")

172

time.sleep(e.retry_after)

173

except TelegraphException as e:

174

print(f"API error on attempt {attempt + 1}: {e}")

175

if attempt == max_retries - 1:

176

raise # Re-raise on final attempt

177

time.sleep(2 ** attempt) # Exponential backoff

178

179

# Usage

180

api = TelegraphApi(access_token='your_token')

181

response = api_call_with_retry(api, 'createPage', {

182

'title': 'Retry Test',

183

'content': '[{"tag": "p", "children": ["Test content"]}]'

184

})

185

```

186

187

### Session Management

188

189

Access underlying HTTP session for advanced configuration:

190

191

```python

192

api = TelegraphApi()

193

194

# Configure session (synchronous API)

195

api.session.headers.update({'User-Agent': 'Custom Telegraph Client'})

196

api.session.timeout = 30

197

198

# Make API calls with custom session settings

199

response = api.method('createAccount', {

200

'short_name': 'session-test'

201

})

202

```

203

204

## Comparison with High-level API

205

206

### High-level API (Telegraph class)

207

- Automatic token management

208

- Convenient parameter handling

209

- Built-in HTML/node conversion

210

- Exception wrapping

211

- Method-specific validation

212

213

### Low-level API (TelegraphApi class)

214

- Direct API access

215

- Manual parameter serialization

216

- Raw response handling

217

- Minimal abstraction

218

- Custom domain support

219

220

Example comparison:

221

222

```python

223

# High-level API

224

from telegraph import Telegraph

225

226

telegraph = Telegraph()

227

response = telegraph.create_page(

228

title='High Level',

229

html_content='<p>Easy to use</p>'

230

)

231

232

# Low-level API

233

from telegraph.api import TelegraphApi

234

import json

235

236

api = TelegraphApi()

237

response = api.method('createPage', {

238

'title': 'Low Level',

239

'content': json.dumps([{'tag': 'p', 'children': ['More control']}],

240

separators=(',', ':'), ensure_ascii=False)

241

})

242

```

243

244

## Use Cases for Low-level API

245

246

1. **Custom Telegraph clients** with specialized features

247

2. **Batch operations** requiring fine-grained control

248

3. **Alternative domain support** for Telegraph mirrors

249

4. **Custom retry and error handling** strategies

250

5. **Performance optimization** by avoiding high-level abstractions

251

6. **Integration with existing HTTP clients** or session management

252

7. **Debugging and testing** Telegraph API responses

253

254

The low-level API provides the foundation for the high-level `Telegraph` class while offering direct access for advanced use cases.