or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-api.mdconfiguration.mdform-fields.mdindex.mdwidgets.md

client-api.mddocs/

0

# Client API

1

2

Low-level client interface for direct interaction with Google's reCAPTCHA verification API. Provides functions for submitting reCAPTCHA responses for validation and handling API responses with comprehensive error handling and proxy support.

3

4

## Capabilities

5

6

### RecaptchaResponse

7

8

Data class encapsulating the response from Google's reCAPTCHA verification API. Contains validation results, error information, and additional data such as V3 scores and actions.

9

10

```python { .api }

11

class RecaptchaResponse:

12

"""

13

Response object from reCAPTCHA API verification.

14

15

Contains validation results and additional response data.

16

"""

17

18

def __init__(self, is_valid, error_codes=None, extra_data=None, action=None):

19

"""

20

Initialize reCAPTCHA response.

21

22

Parameters:

23

- is_valid (bool): Whether reCAPTCHA validation passed

24

- error_codes (list[str], optional): List of error codes from API response

25

- extra_data (dict, optional): Additional response data (score, challenge_ts, etc.)

26

- action (str, optional): reCAPTCHA V3 action name from response

27

"""

28

29

# Attributes

30

is_valid: bool # Validation result

31

error_codes: list[str] # Error codes from API

32

extra_data: dict # Additional response data

33

action: str | None # V3 action name

34

```

35

36

### API Submission

37

38

Core function for submitting reCAPTCHA responses to Google's verification endpoint. Handles HTTP communication, proxy configuration, and response parsing.

39

40

```python { .api }

41

def submit(recaptcha_response, private_key, remoteip):

42

"""

43

Submit reCAPTCHA response for verification.

44

45

Makes HTTP POST request to Google's verification API and returns

46

parsed response data.

47

48

Parameters:

49

- recaptcha_response (str): reCAPTCHA response token from client

50

- private_key (str): Google reCAPTCHA private key

51

- remoteip (str): Client IP address for verification

52

53

Returns:

54

RecaptchaResponse: Parsed API response with validation results

55

56

Raises:

57

HTTPError: If API request fails (timeout, network error, etc.)

58

"""

59

```

60

61

### HTTP Request Handling

62

63

Low-level function for making HTTP requests to Google's reCAPTCHA API with proxy support and custom headers.

64

65

```python { .api }

66

def recaptcha_request(params):

67

"""

68

Make HTTP request to reCAPTCHA API endpoint.

69

70

Handles proxy configuration, custom headers, and timeout settings.

71

72

Parameters:

73

- params (bytes): URL-encoded parameters for API request

74

75

Returns:

76

HTTPResponse: Raw HTTP response from API

77

78

Configuration:

79

- Uses RECAPTCHA_DOMAIN setting for API endpoint

80

- Supports RECAPTCHA_PROXY setting for proxy configuration

81

- Uses RECAPTCHA_VERIFY_REQUEST_TIMEOUT for request timeout

82

"""

83

```

84

85

## API Response Data

86

87

### Successful Response

88

89

For valid reCAPTCHA responses, the API returns:

90

91

- `success: true` - Validation passed

92

- `challenge_ts` - Timestamp of challenge completion

93

- `hostname` - Hostname of site where reCAPTCHA was solved

94

- `score` (V3 only) - Risk score from 0.0 to 1.0

95

- `action` (V3 only) - Action name from request

96

97

### Error Response

98

99

For invalid responses, the API returns error codes:

100

101

- `missing-input-secret` - Secret parameter missing

102

- `invalid-input-secret` - Secret parameter invalid

103

- `missing-input-response` - Response parameter missing

104

- `invalid-input-response` - Response parameter invalid

105

- `bad-request` - Request invalid or malformed

106

- `timeout-or-duplicate` - Response timed out or previously used

107

108

## Configuration

109

110

The client respects Django settings for API configuration:

111

112

- `RECAPTCHA_DOMAIN`: API domain (default: "www.google.com")

113

- `RECAPTCHA_PROXY`: Proxy configuration dictionary

114

- `RECAPTCHA_VERIFY_REQUEST_TIMEOUT`: Request timeout in seconds (default: 10)

115

116

## Usage Examples

117

118

### Direct API Usage

119

120

```python

121

from django_recaptcha.client import submit

122

123

# Submit reCAPTCHA response for verification

124

response = submit(

125

recaptcha_response="03AHJ_ASjdkjf...", # From form submission

126

private_key="6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe",

127

remoteip="192.168.1.100"

128

)

129

130

if response.is_valid:

131

print("reCAPTCHA validation passed")

132

if response.extra_data.get('score'):

133

print(f"V3 Score: {response.extra_data['score']}")

134

else:

135

print(f"Validation failed: {response.error_codes}")

136

```

137

138

### Custom Validation Logic

139

140

```python

141

from django_recaptcha.client import submit

142

from django.core.exceptions import ValidationError

143

144

def validate_recaptcha(token, private_key, client_ip):

145

"""Custom reCAPTCHA validation with error handling."""

146

try:

147

response = submit(token, private_key, client_ip)

148

149

if not response.is_valid:

150

raise ValidationError(

151

f"reCAPTCHA validation failed: {', '.join(response.error_codes)}"

152

)

153

154

# V3 score validation

155

if 'score' in response.extra_data:

156

score = response.extra_data['score']

157

if score < 0.5:

158

raise ValidationError(

159

f"reCAPTCHA score too low: {score}"

160

)

161

162

return response

163

164

except HTTPError as e:

165

raise ValidationError("reCAPTCHA API communication error")

166

```

167

168

### Response Data Access

169

170

```python

171

response = submit(token, private_key, client_ip)

172

173

# Basic validation

174

if response.is_valid:

175

print("Valid reCAPTCHA")

176

177

# Error handling

178

if response.error_codes:

179

for error in response.error_codes:

180

print(f"Error: {error}")

181

182

# V3 specific data

183

if response.action:

184

print(f"Action: {response.action}")

185

186

if 'score' in response.extra_data:

187

score = response.extra_data['score']

188

print(f"Risk score: {score}")

189

190

# Additional metadata

191

if 'challenge_ts' in response.extra_data:

192

timestamp = response.extra_data['challenge_ts']

193

print(f"Challenge completed at: {timestamp}")

194

```

195

196

### Low-level Request Handling

197

198

```python

199

from django_recaptcha.client import recaptcha_request

200

from urllib.parse import urlencode

201

import json

202

203

# Prepare request parameters

204

params = urlencode({

205

'secret': 'your_private_key',

206

'response': 'recaptcha_response_token',

207

'remoteip': '192.168.1.100'

208

}).encode('utf-8')

209

210

# Make direct API request

211

try:

212

http_response = recaptcha_request(params)

213

data = json.loads(http_response.read().decode('utf-8'))

214

http_response.close()

215

216

print(f"API Response: {data}")

217

218

except Exception as e:

219

print(f"Request failed: {e}")

220

```