0
# Generated Code API
1
2
The generated code API provides validation methods and utilities for each target language. The specific API varies by language but provides consistent validation functionality across all supported platforms.
3
4
## Go Generated Code
5
6
Go code generation produces validation methods directly on protobuf message types with zero runtime dependencies.
7
8
### Validation Methods
9
10
```go { .api }
11
func (m *Message) Validate() error
12
```
13
14
Validates the message according to its validation rules, returning the first error encountered.
15
16
**Returns:** `error` - First validation error, or `nil` if valid
17
18
**Behavior:**
19
- Returns immediately on first validation failure
20
- Validates nested messages recursively (unless skipped)
21
- Provides detailed error messages with field context
22
- Zero allocations for valid messages
23
24
Usage:
25
```go
26
user := &User{Email: "invalid-email"}
27
if err := user.Validate(); err != nil {
28
log.Printf("Validation failed: %v", err)
29
}
30
```
31
32
```go { .api }
33
func (m *Message) ValidateAll() error
34
```
35
36
Validates the message and collects all validation errors into a single error.
37
38
**Returns:** `error` - Combined validation errors, or `nil` if valid
39
40
**Behavior:**
41
- Continues validation after first error
42
- Collects all validation failures
43
- Returns structured error with all field errors
44
- Useful for form validation scenarios
45
46
Usage:
47
```go
48
user := &User{Email: "invalid", Age: -1}
49
if err := user.ValidateAll(); err != nil {
50
// err contains both email and age validation errors
51
log.Printf("All validation errors: %v", err)
52
}
53
```
54
55
### Error Types
56
57
Generated Go code uses standard `error` interface with descriptive messages:
58
59
```go
60
// Example error messages
61
"invalid User.Email: value must be a valid email address"
62
"invalid User.Age: value must be greater than 0"
63
"invalid User.Name: value length must be at least 1 characters"
64
```
65
66
### Integration
67
68
Generated validation integrates seamlessly with existing Go protobuf code:
69
70
```go
71
import (
72
"github.com/example/proto/user"
73
// validation methods are automatically available
74
)
75
76
func processUser(u *user.User) error {
77
if err := u.Validate(); err != nil {
78
return fmt.Errorf("invalid user: %w", err)
79
}
80
// process valid user
81
return nil
82
}
83
```
84
85
## Java Generated Code
86
87
Java code generation produces validator classes with reflection-based validation and gRPC integration support.
88
89
### Validator Interface
90
91
```java { .api }
92
interface Validator<T> {
93
void assertValid(T message) throws ValidationException;
94
}
95
```
96
97
Base interface for all generated validators.
98
99
**Type Parameters:**
100
- `T`: Message type being validated
101
102
**Methods:**
103
- `assertValid(T message)`: Validates message, throws on failure
104
105
### Validator Index
106
107
```java { .api }
108
class ReflectiveValidatorIndex {
109
public Validator validatorFor(Class<?> clazz);
110
}
111
```
112
113
Main entry point for accessing validators by message class.
114
115
**Methods:**
116
- `validatorFor(Class<?> clazz)`: Returns validator for message class
117
118
**Usage:**
119
```java
120
ValidatorIndex index = new ReflectiveValidatorIndex();
121
Validator<User> userValidator = index.validatorFor(User.class);
122
userValidator.assertValid(user); // throws ValidationException if invalid
123
```
124
125
### gRPC Integration
126
127
```java { .api }
128
class ValidatingClientInterceptor implements ClientInterceptor
129
class ValidatingServerInterceptor implements ServerInterceptor
130
```
131
132
gRPC interceptors for automatic request/response validation.
133
134
**Usage:**
135
```java
136
// Client-side validation
137
clientStub = clientStub.withInterceptors(new ValidatingClientInterceptor(index));
138
139
// Server-side validation
140
serverBuilder.addService(
141
ServerInterceptors.intercept(service, new ValidatingServerInterceptor(index))
142
);
143
```
144
145
### Exception Handling
146
147
```java { .api }
148
class ValidationException extends Exception {
149
public ValidationException(String message);
150
public String getFieldPath();
151
public Object getInvalidValue();
152
}
153
```
154
155
Exception thrown when validation fails.
156
157
**Methods:**
158
- `getFieldPath()`: Returns field path that failed validation
159
- `getInvalidValue()`: Returns the invalid value
160
161
## C++ Generated Code
162
163
C++ code generation produces validation functions with string-based error reporting.
164
165
### Validation Functions
166
167
```cpp { .api }
168
bool Validate(const Message& msg, std::string* error = nullptr);
169
```
170
171
Validates a message and optionally returns error details.
172
173
**Parameters:**
174
- `msg`: Const reference to message to validate
175
- `error`: Optional pointer to string for error details
176
177
**Returns:** `bool` - `true` if valid, `false` if invalid
178
179
**Usage:**
180
```cpp
181
User user;
182
user.set_email("invalid-email");
183
184
std::string error;
185
if (!Validate(user, &error)) {
186
std::cerr << "Validation failed: " << error << std::endl;
187
}
188
```
189
190
### Namespace Organization
191
192
Generated C++ code is organized in the `validate` namespace:
193
194
```cpp
195
namespace validate {
196
bool Validate(const example::User& msg, std::string* error);
197
bool Validate(const example::Order& msg, std::string* error);
198
// ... other message validators
199
}
200
```
201
202
### Header/Implementation Split
203
204
C++ generation produces separate header and implementation files:
205
206
**Header (.pb.validate.h):**
207
- Function declarations
208
- Include dependencies
209
- Namespace definitions
210
211
**Implementation (.pb.validate.cc):**
212
- Function implementations
213
- Validation logic
214
- Error message generation
215
216
## Python Runtime API
217
218
Python uses runtime code generation with dynamic validation function creation.
219
220
### Validation Function
221
222
```python { .api }
223
def validate(msg) -> None
224
```
225
226
Validates a protobuf message instance, raising exception on failure.
227
228
**Parameters:**
229
- `msg`: Protobuf message instance to validate
230
231
**Raises:** `ValidationFailed` - When validation fails
232
233
**Usage:**
234
```python
235
from entities_pb2 import User
236
from protoc_gen_validate.validator import validate, ValidationFailed
237
238
user = User(email="invalid-email")
239
try:
240
validate(user)
241
except ValidationFailed as e:
242
print(f"Validation failed: {e}")
243
```
244
245
### Debug Function
246
247
```python { .api }
248
def print_validate(msg) -> None
249
```
250
251
Prints the generated validation code for debugging purposes.
252
253
**Parameters:**
254
- `msg`: Protobuf message instance
255
256
**Behavior:**
257
- Generates validation function code dynamically
258
- Prints the generated Python code to stdout
259
- Useful for debugging validation logic
260
261
**Usage:**
262
```python
263
from protoc_gen_validate.validator import print_validate
264
265
user = User()
266
print_validate(user) # Prints generated validation function
267
```
268
269
### Exception Type
270
271
```python { .api }
272
class ValidationFailed(Exception):
273
"""Raised when message validation fails"""
274
pass
275
```
276
277
Exception raised when validation fails.
278
279
**Inheritance:** Standard Python `Exception`
280
281
**Usage:**
282
```python
283
try:
284
validate(message)
285
except ValidationFailed as e:
286
logger.error(f"Invalid message: {e}")
287
```
288
289
### Performance Features
290
291
Python runtime includes performance optimizations:
292
293
- **LRU Cache**: Compiled validation functions are cached by message descriptor
294
- **JIT Compilation**: Validation functions generated on-demand using `exec()`
295
- **Lazy Loading**: Functions only generated when first needed
296
297
## Cross-Language Consistency
298
299
All generated code maintains consistent behavior across languages:
300
301
### Validation Semantics
302
- Same validation rules produce same results
303
- Consistent error detection and reporting
304
- Identical handling of edge cases and special values
305
306
### Error Messages
307
- Similar error message patterns across languages
308
- Field path information included where possible
309
- Descriptive error text for debugging
310
311
### Performance Characteristics
312
- Minimal overhead for valid messages
313
- Early termination on first error (where applicable)
314
- Efficient nested message validation
315
316
## Integration Patterns
317
318
### Framework Integration
319
320
**Go:**
321
- HTTP middleware for request validation
322
- gRPC interceptors
323
- Database model validation
324
325
**Java:**
326
- Spring Boot validation integration
327
- JAX-RS request validation
328
- gRPC service validation
329
330
**C++:**
331
- Service layer validation
332
- Protocol buffer message verification
333
- API boundary checking
334
335
**Python:**
336
- Django/Flask request validation
337
- Celery task parameter validation
338
- API endpoint validation
339
340
### Testing Support
341
342
All generated code supports testing scenarios:
343
344
- Mock validation for unit tests
345
- Validation bypass for test data setup
346
- Error injection for negative testing
347
- Performance benchmarking utilities