0
# Data Model Documentation
1
2
Annotations for documenting data models, their properties, and relationships. These annotations provide detailed metadata about the structure, constraints, and documentation for data transfer objects and entity classes used in API requests and responses.
3
4
## Capabilities
5
6
### @ApiModel Annotation
7
8
Provides additional information about Swagger models. Classes are automatically introspected when used as types in operations, but this annotation allows manipulation of the model structure.
9
10
```java { .api }
11
/**
12
* Provides additional information about Swagger models
13
* Classes are introspected automatically, this allows structure manipulation
14
* Target: TYPE (classes)
15
* Retention: RUNTIME
16
* Inherited: true
17
*/
18
@Target({ElementType.TYPE})
19
@Retention(RetentionPolicy.RUNTIME)
20
@Inherited
21
@interface ApiModel {
22
/**
23
* Provide an alternative name for the model
24
* By default, the class name is used
25
*/
26
String value() default "";
27
28
/** Provide a longer description of the class */
29
String description() default "";
30
31
/** Provide a superclass for the model to allow describing inheritance */
32
Class<?> parent() default Void.class;
33
34
/**
35
* Supports model inheritance and polymorphism
36
* Name of the field used as a discriminator for asserting sub type
37
*/
38
String discriminator() default "";
39
40
/** Array of sub types inheriting from this model */
41
Class<?>[] subTypes() default {};
42
43
/**
44
* Specifies a reference to the corresponding type definition
45
* Overrides any other metadata specified
46
*/
47
String reference() default "";
48
}
49
```
50
51
**Usage Examples:**
52
53
```java
54
// Basic model documentation
55
@ApiModel(description = "User account information")
56
public class User {
57
// properties
58
}
59
60
// Model with alternative name
61
@ApiModel(
62
value = "UserAccount",
63
description = "Complete user account with profile and settings"
64
)
65
public class User {
66
// properties
67
}
68
69
// Inheritance and polymorphism
70
@ApiModel(
71
description = "Base shape class",
72
discriminator = "shapeType",
73
subTypes = {Circle.class, Rectangle.class, Triangle.class}
74
)
75
public abstract class Shape {
76
@ApiModelProperty(value = "Type of shape", required = true)
77
private String shapeType;
78
79
// common properties
80
}
81
82
@ApiModel(description = "Circle shape")
83
public class Circle extends Shape {
84
@ApiModelProperty(value = "Circle radius", required = true)
85
private double radius;
86
}
87
88
@ApiModel(description = "Rectangle shape")
89
public class Rectangle extends Shape {
90
@ApiModelProperty(value = "Rectangle width", required = true)
91
private double width;
92
93
@ApiModelProperty(value = "Rectangle height", required = true)
94
private double height;
95
}
96
```
97
98
### @ApiModelProperty Annotation
99
100
Adds and manipulates data of a model property. Can be used on fields or getter methods.
101
102
```java { .api }
103
/**
104
* Adds and manipulates data of a model property
105
* Target: METHOD (getters), FIELD
106
* Retention: RUNTIME
107
*/
108
@Target({ElementType.METHOD, ElementType.FIELD})
109
@Retention(RetentionPolicy.RUNTIME)
110
@interface ApiModelProperty {
111
/** Brief description of the property */
112
String value() default "";
113
114
/**
115
* Override the name of the property
116
* By default, field name or getter method name is used
117
*/
118
String name() default "";
119
120
/**
121
* Limits allowable values for this property
122
* Same format as @ApiParam allowableValues:
123
* - List: "first, second, third"
124
* - Range: "range[1, 5]", "range(1, 5)", "range[1, 5)"
125
* - Min/Max: "range[1, infinity]", "range[-infinity, 100]"
126
*/
127
String allowableValues() default "";
128
129
/**
130
* Property access level for filtering
131
* See io.swagger.core.filter.SwaggerSpecFilter for details
132
*/
133
String access() default "";
134
135
/** Additional notes about the property */
136
String notes() default "";
137
138
/**
139
* Data type of the property
140
* Override automatically detected type
141
*/
142
String dataType() default "";
143
144
/** Specifies if the property is required */
145
boolean required() default false;
146
147
/**
148
* Position of property in model
149
* Used for ordering properties in documentation
150
*/
151
int position() default 0;
152
153
/** Hides the property from model documentation */
154
boolean hidden() default false;
155
156
/** Example value for the property */
157
String example() default "";
158
159
/**
160
* Specifies that property is read-only
161
* Property will be sent in response but not expected in request
162
* @deprecated As of 1.5.19, replaced by accessMode()
163
*/
164
@Deprecated
165
boolean readOnly() default false;
166
167
/**
168
* Allows specifying the access mode of a model property
169
* @since 1.5.19
170
*/
171
AccessMode accessMode() default AccessMode.AUTO;
172
173
/**
174
* Specifies a reference to corresponding property definition
175
* Overrides other metadata if specified
176
*/
177
String reference() default "";
178
179
/** Specifies that property allows empty values */
180
boolean allowEmptyValue() default false;
181
182
/** Optional array of extensions */
183
Extension[] extensions() default @Extension(properties = @ExtensionProperty(name = "", value = ""));
184
}
185
```
186
187
**Usage Examples:**
188
189
```java
190
@ApiModel(description = "User account")
191
public class User {
192
193
@ApiModelProperty(
194
value = "Unique user identifier",
195
example = "12345",
196
readOnly = true,
197
position = 1
198
)
199
private Long id;
200
201
@ApiModelProperty(
202
value = "User's full name",
203
required = true,
204
example = "John Doe",
205
position = 2
206
)
207
private String name;
208
209
@ApiModelProperty(
210
value = "Email address",
211
required = true,
212
example = "john.doe@example.com",
213
notes = "Must be a valid email format",
214
position = 3
215
)
216
private String email;
217
218
@ApiModelProperty(
219
value = "User age",
220
allowableValues = "range[13, 120]",
221
example = "25",
222
position = 4
223
)
224
private Integer age;
225
226
@ApiModelProperty(
227
value = "Account status",
228
allowableValues = "ACTIVE, INACTIVE, SUSPENDED, PENDING",
229
example = "ACTIVE",
230
position = 5
231
)
232
private UserStatus status;
233
234
@ApiModelProperty(
235
value = "Account creation timestamp",
236
example = "2023-01-15T10:30:00Z",
237
readOnly = true,
238
dataType = "string",
239
notes = "ISO 8601 timestamp format"
240
)
241
private LocalDateTime createdAt;
242
243
@ApiModelProperty(hidden = true)
244
private String internalId;
245
246
// Getters and setters
247
}
248
249
// Using on getter methods
250
@ApiModel(description = "Product information")
251
public class Product {
252
private String name;
253
private BigDecimal price;
254
private String currency;
255
256
@ApiModelProperty(
257
value = "Product name",
258
required = true,
259
example = "Wireless Headphones"
260
)
261
public String getName() {
262
return name;
263
}
264
265
@ApiModelProperty(
266
value = "Formatted price string",
267
example = "$99.99 USD",
268
readOnly = true
269
)
270
public String getFormattedPrice() {
271
return String.format("$%.2f %s", price, currency);
272
}
273
}
274
```
275
276
### Complex Model Patterns
277
278
#### Nested Models
279
280
```java
281
@ApiModel(description = "User profile with address")
282
public class UserProfile {
283
284
@ApiModelProperty(value = "Basic user information", required = true)
285
private User user;
286
287
@ApiModelProperty(value = "Home address")
288
private Address homeAddress;
289
290
@ApiModelProperty(value = "Work address")
291
private Address workAddress;
292
}
293
294
@ApiModel(description = "Address information")
295
public class Address {
296
297
@ApiModelProperty(value = "Street address", required = true, example = "123 Main St")
298
private String street;
299
300
@ApiModelProperty(value = "City", required = true, example = "Springfield")
301
private String city;
302
303
@ApiModelProperty(value = "State or province", example = "IL")
304
private String state;
305
306
@ApiModelProperty(value = "Postal code", example = "62701")
307
private String postalCode;
308
309
@ApiModelProperty(
310
value = "Country code",
311
example = "US",
312
allowableValues = "US, CA, MX, UK, DE, FR"
313
)
314
private String country;
315
}
316
```
317
318
#### Collections and Arrays
319
320
```java
321
@ApiModel(description = "Shopping cart")
322
public class ShoppingCart {
323
324
@ApiModelProperty(value = "Cart items")
325
private List<CartItem> items;
326
327
@ApiModelProperty(value = "Applied discount codes")
328
private Set<String> discountCodes;
329
330
@ApiModelProperty(
331
value = "Item quantities by product ID",
332
dataType = "java.util.Map"
333
)
334
private Map<Long, Integer> quantities;
335
}
336
337
@ApiModel(description = "Cart item")
338
public class CartItem {
339
340
@ApiModelProperty(value = "Product information", required = true)
341
private Product product;
342
343
@ApiModelProperty(
344
value = "Quantity",
345
required = true,
346
allowableValues = "range[1, 99]",
347
example = "2"
348
)
349
private Integer quantity;
350
351
@ApiModelProperty(value = "Line total", readOnly = true)
352
private BigDecimal lineTotal;
353
}
354
```
355
356
#### Generic Types
357
358
```java
359
@ApiModel(description = "Generic API response wrapper")
360
public class ApiResponse<T> {
361
362
@ApiModelProperty(value = "Success status", example = "true")
363
private boolean success;
364
365
@ApiModelProperty(value = "Response message", example = "Operation completed successfully")
366
private String message;
367
368
@ApiModelProperty(value = "Response data")
369
private T data;
370
371
@ApiModelProperty(value = "Error details")
372
private List<String> errors;
373
374
@ApiModelProperty(value = "Response timestamp", readOnly = true)
375
private LocalDateTime timestamp;
376
}
377
378
// Usage in operations
379
@ApiOperation(
380
value = "Get user",
381
response = ApiResponse.class,
382
notes = "Returns user data wrapped in generic response"
383
)
384
@GET
385
@Path("/{id}")
386
public ApiResponse<User> getUser(@PathParam("id") Long id) {
387
// implementation
388
}
389
```
390
391
#### Validation Constraints
392
393
```java
394
@ApiModel(description = "User registration request")
395
public class UserRegistrationRequest {
396
397
@ApiModelProperty(
398
value = "Username",
399
required = true,
400
allowableValues = "range[3, 50]",
401
example = "johndoe",
402
notes = "Must be unique, alphanumeric characters and underscores only"
403
)
404
private String username;
405
406
@ApiModelProperty(
407
value = "Password",
408
required = true,
409
allowableValues = "range[8, 128]",
410
notes = "Must contain at least one letter, one number, and one special character"
411
)
412
private String password;
413
414
@ApiModelProperty(
415
value = "Email address",
416
required = true,
417
example = "john@example.com",
418
notes = "Must be valid email format"
419
)
420
private String email;
421
422
@ApiModelProperty(
423
value = "Date of birth",
424
example = "1990-01-15",
425
dataType = "string",
426
notes = "ISO date format (YYYY-MM-DD), user must be at least 13 years old"
427
)
428
private LocalDate dateOfBirth;
429
430
@ApiModelProperty(
431
value = "Terms acceptance",
432
required = true,
433
allowableValues = "true",
434
notes = "Must be true to register"
435
)
436
private Boolean acceptTerms;
437
}
438
```
439
440
### Core Model Types
441
442
```java { .api }
443
/**
444
* Access mode for model properties
445
* @since 1.5.19
446
*/
447
enum AccessMode {
448
/** Automatically determine access mode based on context */
449
AUTO,
450
/** Property is read-only (response only) */
451
READ_ONLY,
452
/** Property is read-write (request and response) */
453
READ_WRITE
454
}
455
```
456
457
### Enums and Constants
458
459
```java
460
@ApiModel(description = "User account status")
461
public enum UserStatus {
462
@ApiModelProperty("Active user account")
463
ACTIVE,
464
465
@ApiModelProperty("Temporarily inactive account")
466
INACTIVE,
467
468
@ApiModelProperty("Suspended due to policy violation")
469
SUSPENDED,
470
471
@ApiModelProperty("Pending email verification")
472
PENDING_VERIFICATION,
473
474
@ApiModelProperty("Account marked for deletion")
475
PENDING_DELETION;
476
}
477
478
@ApiModel(description = "Application constants")
479
public class AppConstants {
480
481
@ApiModelProperty(value = "Maximum file upload size in bytes", example = "10485760")
482
public static final long MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
483
484
@ApiModelProperty(value = "Supported file types")
485
public static final String[] SUPPORTED_FILE_TYPES = {"jpg", "png", "pdf", "doc", "docx"};
486
487
@ApiModelProperty(value = "Default page size for pagination", example = "20")
488
public static final int DEFAULT_PAGE_SIZE = 20;
489
}
490
```
491
492
### Best Practices
493
494
1. **Document all public models** - Any class used in API requests/responses should have @ApiModel
495
2. **Use meaningful descriptions** - Provide clear, concise descriptions for models and properties
496
3. **Include examples** - Help developers understand expected data format
497
4. **Mark required properties** - Use `required = true` for mandatory fields
498
5. **Use appropriate positioning** - Order properties logically with `position` attribute
499
6. **Document constraints** - Use `allowableValues` for validation rules
500
7. **Handle inheritance properly** - Use `discriminator` and `subTypes` for polymorphic models
501
8. **Mark read-only fields** - Use `readOnly = true` for computed or auto-generated properties
502
9. **Hide internal properties** - Use `hidden = true` for properties not exposed in API
503
10. **Provide validation notes** - Include validation rules and constraints in `notes`