or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdcore-messaging.mderror-handling.mdindex.md

core-messaging.mddocs/

0

# Core Messaging

1

2

PyFCM's core messaging functionality provides comprehensive support for sending push notifications through Firebase Cloud Messaging HTTP v1 API. The system supports multiple targeting methods, message types, and platform-specific configurations.

3

4

## Capabilities

5

6

### FCMNotification Class

7

8

Main client class for Firebase Cloud Messaging operations, handling authentication, request management, and message delivery.

9

10

```python { .api }

11

class FCMNotification:

12

def __init__(

13

service_account_file: Optional[str] = None,

14

project_id: Optional[str] = None,

15

credentials: Optional[Credentials] = None,

16

proxy_dict: Optional[dict] = None,

17

env: Optional[str] = None,

18

json_encoder=None,

19

adapter=None

20

):

21

"""

22

Initialize FCM client.

23

24

Parameters:

25

- service_account_file: Path to service account JSON file

26

- project_id: Google Cloud project ID

27

- credentials: Google OAuth2 credentials instance (ADC, etc.)

28

- proxy_dict: Proxy configuration {"http": "...", "https": "..."}

29

- env: Environment setting ("app_engine" for App Engine)

30

- json_encoder: Custom JSON encoder class

31

- adapter: Custom HTTP adapter instance

32

"""

33

```

34

35

### Notification Messaging

36

37

Send display notifications that appear in the device's notification tray with title, body, and optional image.

38

39

```python { .api }

40

def notify(

41

fcm_token=None,

42

notification_title=None,

43

notification_body=None,

44

notification_image=None,

45

data_payload=None,

46

topic_name=None,

47

topic_condition=None,

48

android_config=None,

49

apns_config=None,

50

webpush_config=None,

51

fcm_options=None,

52

dry_run=False,

53

timeout=120

54

):

55

"""

56

Send push notification to device, topic, or conditional target.

57

58

Parameters:

59

- fcm_token (str, optional): FCM device registration token

60

- notification_title (str, optional): Notification title text

61

- notification_body (str, optional): Notification body text

62

- notification_image (str, optional): Image URL for notification

63

- data_payload (dict, optional): Custom key-value data payload

64

- topic_name (str, optional): Topic name for broadcasting

65

- topic_condition (str, optional): Boolean topic condition expression

66

- android_config (dict, optional): Android-specific message options

67

- apns_config (dict, optional): Apple Push Notification options

68

- webpush_config (dict, optional): Web push protocol options

69

- fcm_options (dict, optional): Platform-independent FCM options

70

- dry_run (bool, optional): Validate without sending (default: False)

71

- timeout (int, optional): Request timeout seconds (default: 120)

72

73

Returns:

74

dict: Response containing message name/ID

75

76

Raises:

77

AuthenticationError: Invalid credentials or authentication failure

78

InvalidDataError: Malformed data or missing required parameters

79

FCMServerError: FCM service temporarily unavailable

80

FCMNotRegisteredError: Invalid or unregistered device token

81

FCMSenderIdMismatchError: Token sender mismatch

82

"""

83

```

84

85

### Data Messaging

86

87

Send data-only messages containing custom key-value pairs that are processed by the client application without displaying notifications.

88

89

```python

90

# Data-only message (no notification display)

91

data_payload = {

92

"action": "sync_data",

93

"user_id": "12345",

94

"timestamp": "2024-01-01T00:00:00Z"

95

}

96

97

result = fcm.notify(

98

fcm_token="device_token",

99

data_payload=data_payload

100

)

101

```

102

103

### Topic Messaging

104

105

Broadcast messages to devices subscribed to specific topics or topic condition expressions.

106

107

```python

108

# Send to topic subscribers

109

result = fcm.notify(

110

topic_name="news",

111

notification_title="Breaking News",

112

notification_body="Important update"

113

)

114

115

# Conditional topic messaging

116

topic_condition = "'sports' in topics && ('basketball' in topics || 'football' in topics)"

117

result = fcm.notify(

118

topic_condition=topic_condition,

119

notification_title="Sports Update",

120

notification_body="Game results are in!"

121

)

122

```

123

124

### Platform-Specific Configuration

125

126

Configure platform-specific options for Android, iOS, and Web platforms using dedicated configuration objects.

127

128

```python

129

# Android-specific configuration

130

android_config = {

131

"notification": {

132

"icon": "stock_ticker_update",

133

"color": "#f45342"

134

},

135

"data": {

136

"click_action": "FLUTTER_NOTIFICATION_CLICK"

137

}

138

}

139

140

# iOS-specific configuration

141

apns_config = {

142

"headers": {

143

"apns-priority": "10"

144

},

145

"payload": {

146

"aps": {

147

"alert": {

148

"title": "Custom Title",

149

"body": "Custom Body"

150

},

151

"badge": 42

152

}

153

}

154

}

155

156

# Web push configuration

157

webpush_config = {

158

"headers": {

159

"TTL": "86400"

160

},

161

"notification": {

162

"icon": "https://example.com/icon.png",

163

"actions": [

164

{

165

"action": "view",

166

"title": "View Details"

167

}

168

]

169

}

170

}

171

172

result = fcm.notify(

173

fcm_token="device_token",

174

notification_title="Multi-platform Message",

175

android_config=android_config,

176

apns_config=apns_config,

177

webpush_config=webpush_config

178

)

179

```

180

181

### Authentication Methods

182

183

Multiple authentication methods including service account files, Google OAuth2 credentials, and environment variables.

184

185

```python

186

# Service account file authentication

187

fcm = FCMNotification(

188

service_account_file="path/to/service-account.json",

189

project_id="your-project-id"

190

)

191

192

# Google OAuth2 credentials (ADC, impersonation, etc.)

193

from google.oauth2 import service_account

194

credentials = service_account.Credentials.from_service_account_info(

195

credential_dict,

196

scopes=['https://www.googleapis.com/auth/firebase.messaging']

197

)

198

fcm = FCMNotification(

199

credentials=credentials,

200

project_id="your-project-id"

201

)

202

203

# With proxy configuration

204

proxy_dict = {

205

"http": "http://proxy.example.com:8080",

206

"https": "http://proxy.example.com:8080"

207

}

208

fcm = FCMNotification(

209

service_account_file="service-account.json",

210

project_id="your-project-id",

211

proxy_dict=proxy_dict

212

)

213

```

214

215

### Utility Methods

216

217

Core utility methods available on FCMNotification instances for advanced use cases and custom request handling.

218

219

```python { .api }

220

def json_dumps(self, data):

221

"""

222

Standardized JSON serialization with FCM-compatible formatting.

223

224

Parameters:

225

- data: Dictionary or list to be serialized

226

227

Returns:

228

bytes: UTF-8 encoded JSON with sorted keys and separators

229

"""

230

231

def parse_response(self, response):

232

"""

233

Parse FCM HTTP response and handle error conditions.

234

235

Parameters:

236

- response: HTTP response object from requests

237

238

Returns:

239

dict: Parsed response data containing message identifier

240

241

Raises:

242

AuthenticationError: Authentication failure (401)

243

InvalidDataError: Malformed request data (400)

244

FCMSenderIdMismatchError: Sender authorization error (403)

245

FCMNotRegisteredError: Invalid token (404)

246

FCMServerError: Server errors and timeouts (5xx)

247

"""

248

249

def parse_payload(

250

self,

251

fcm_token=None,

252

notification_title=None,

253

notification_body=None,

254

notification_image=None,

255

data_payload=None,

256

topic_name=None,

257

topic_condition=None,

258

android_config=None,

259

apns_config=None,

260

webpush_config=None,

261

fcm_options=None,

262

dry_run=False

263

):

264

"""

265

Convert notification parameters into FCM-compatible JSON payload.

266

267

Parameters: Same as notify() method

268

269

Returns:

270

bytes: JSON payload ready for FCM API request

271

272

Raises:

273

InvalidDataError: Invalid configuration format or data

274

"""

275

```

276

277

## Types

278

279

```python { .api }

280

# From google.oauth2.credentials

281

class Credentials:

282

"""Google OAuth2 credentials for authentication"""

283

284

# Response format

285

ResponseDict = dict # Contains "name" key with message identifier

286

287

# Configuration dictionaries

288

AndroidConfig = dict # Android-specific message configuration

289

APNSConfig = dict # Apple Push Notification Service configuration

290

WebpushConfig = dict # Web push protocol configuration

291

FCMOptions = dict # Platform-independent FCM options

292

```