|
| 1 | +# Examples |
| 2 | + |
| 3 | +This page provides comprehensive examples of using Jazzy Framework in different scenarios. |
| 4 | + |
| 5 | +## Basic REST API |
| 6 | + |
| 7 | +Here's a complete example of a basic REST API for a user management system: |
| 8 | + |
| 9 | +```java |
| 10 | +import static jazzyframework.http.ResponseFactory.response; |
| 11 | +import jazzyframework.http.Request; |
| 12 | +import jazzyframework.http.Response; |
| 13 | +import jazzyframework.http.validation.ValidationResult; |
| 14 | +import jazzyframework.routing.Router; |
| 15 | + |
| 16 | +public class UserApi { |
| 17 | + |
| 18 | + public static void main(String[] args) { |
| 19 | + // Create a new router |
| 20 | + Router router = new Router(); |
| 21 | + |
| 22 | + // Define routes |
| 23 | + router.get("/api/users", UserApi::getAllUsers); |
| 24 | + router.get("/api/users/{id}", UserApi::getUserById); |
| 25 | + router.post("/api/users", UserApi::createUser); |
| 26 | + router.put("/api/users/{id}", UserApi::updateUser); |
| 27 | + router.delete("/api/users/{id}", UserApi::deleteUser); |
| 28 | + |
| 29 | + // Start the server |
| 30 | + router.startServer(8080); |
| 31 | + } |
| 32 | + |
| 33 | + // Get all users |
| 34 | + public static Response getAllUsers(Request request) { |
| 35 | + // Get query parameters for pagination |
| 36 | + int page = request.queryInt("page", 1); |
| 37 | + int limit = request.queryInt("limit", 10); |
| 38 | + |
| 39 | + // Fetch users from database (example) |
| 40 | + List<User> users = UserService.getUsers(page, limit); |
| 41 | + int total = UserService.countUsers(); |
| 42 | + |
| 43 | + return response().json( |
| 44 | + "users", users, |
| 45 | + "page", page, |
| 46 | + "limit", limit, |
| 47 | + "total", total |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + // Get user by ID |
| 52 | + public static Response getUserById(Request request) { |
| 53 | + String id = request.path("id"); |
| 54 | + |
| 55 | + // Find user |
| 56 | + User user = UserService.findById(id); |
| 57 | + |
| 58 | + if (user == null) { |
| 59 | + return response().json( |
| 60 | + "status", "error", |
| 61 | + "message", "User not found" |
| 62 | + ).status(404); |
| 63 | + } |
| 64 | + |
| 65 | + return response().json(user); |
| 66 | + } |
| 67 | + |
| 68 | + // Create new user |
| 69 | + public static Response createUser(Request request) { |
| 70 | + // Validate input |
| 71 | + ValidationResult result = request.validator() |
| 72 | + .field("name").required().minLength(3) |
| 73 | + .field("email").required().email() |
| 74 | + .field("password").required().minLength(8) |
| 75 | + .validate(); |
| 76 | + |
| 77 | + if (!result.isValid()) { |
| 78 | + return response().json( |
| 79 | + "status", "error", |
| 80 | + "message", "Validation failed", |
| 81 | + "errors", result.getAllErrors() |
| 82 | + ).status(400); |
| 83 | + } |
| 84 | + |
| 85 | + // Parse JSON data |
| 86 | + Map<String, Object> userData = request.parseJson(); |
| 87 | + |
| 88 | + // Create user (example) |
| 89 | + User newUser = UserService.createUser( |
| 90 | + (String) userData.get("name"), |
| 91 | + (String) userData.get("email"), |
| 92 | + (String) userData.get("password") |
| 93 | + ); |
| 94 | + |
| 95 | + // Return response with created user |
| 96 | + return response().json( |
| 97 | + "status", "success", |
| 98 | + "message", "User created successfully", |
| 99 | + "user", newUser |
| 100 | + ).status(201); |
| 101 | + } |
| 102 | + |
| 103 | + // Update user |
| 104 | + public static Response updateUser(Request request) { |
| 105 | + String id = request.path("id"); |
| 106 | + |
| 107 | + // Check if user exists |
| 108 | + if (!UserService.exists(id)) { |
| 109 | + return response().json( |
| 110 | + "status", "error", |
| 111 | + "message", "User not found" |
| 112 | + ).status(404); |
| 113 | + } |
| 114 | + |
| 115 | + // Validate input |
| 116 | + ValidationResult result = request.validator() |
| 117 | + .field("name").optional().minLength(3) |
| 118 | + .field("email").optional().email() |
| 119 | + .validate(); |
| 120 | + |
| 121 | + if (!result.isValid()) { |
| 122 | + return response().json( |
| 123 | + "status", "error", |
| 124 | + "message", "Validation failed", |
| 125 | + "errors", result.getAllErrors() |
| 126 | + ).status(400); |
| 127 | + } |
| 128 | + |
| 129 | + // Parse JSON data |
| 130 | + Map<String, Object> userData = request.parseJson(); |
| 131 | + |
| 132 | + // Update user (example) |
| 133 | + User updatedUser = UserService.updateUser(id, userData); |
| 134 | + |
| 135 | + return response().success("User updated successfully", updatedUser); |
| 136 | + } |
| 137 | + |
| 138 | + // Delete user |
| 139 | + public static Response deleteUser(Request request) { |
| 140 | + String id = request.path("id"); |
| 141 | + |
| 142 | + // Check if user exists |
| 143 | + if (!UserService.exists(id)) { |
| 144 | + return response().json( |
| 145 | + "status", "error", |
| 146 | + "message", "User not found" |
| 147 | + ).status(404); |
| 148 | + } |
| 149 | + |
| 150 | + // Delete user |
| 151 | + UserService.deleteUser(id); |
| 152 | + |
| 153 | + return response().success("User deleted successfully"); |
| 154 | + } |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +## Data Validation Example |
| 159 | + |
| 160 | +Here's an example of using complex validation with custom validation rules: |
| 161 | + |
| 162 | +```java |
| 163 | +import jazzyframework.http.validation.ValidationRules; |
| 164 | + |
| 165 | +// Create a validation rules class |
| 166 | +public class ProductCreateRules extends ValidationRules { |
| 167 | + |
| 168 | + public ProductCreateRules() { |
| 169 | + field("name").required().minLength(3).maxLength(100); |
| 170 | + field("price").required().min(0.01); |
| 171 | + field("description").optional().maxLength(1000); |
| 172 | + field("category").required().in("electronics", "clothing", "food", "books"); |
| 173 | + field("tags").optional(); |
| 174 | + field("stock").required().min(0); |
| 175 | + field("sku").required().pattern("^[A-Z]{2}-\\d{4}-[A-Z]{2}$", |
| 176 | + "SKU must be in format XX-0000-XX"); |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +// Use in controller |
| 181 | +public Response createProduct(Request request) { |
| 182 | + ValidationResult result = request.validate(new ProductCreateRules()); |
| 183 | + |
| 184 | + if (!result.isValid()) { |
| 185 | + return response().json( |
| 186 | + "status", "error", |
| 187 | + "message", "Validation failed", |
| 188 | + "errors", result.getAllErrors() |
| 189 | + ).status(400); |
| 190 | + } |
| 191 | + |
| 192 | + // Convert JSON data to Product object |
| 193 | + Product product = request.toObject(Product.class); |
| 194 | + |
| 195 | + // Save product |
| 196 | + productRepository.save(product); |
| 197 | + |
| 198 | + // Return success response |
| 199 | + return response().success("Product created successfully", product) |
| 200 | + .status(201); |
| 201 | +} |
| 202 | +``` |
| 203 | + |
| 204 | +## File Upload API |
| 205 | + |
| 206 | +Here's how to handle file uploads in Jazzy: |
| 207 | + |
| 208 | +```java |
| 209 | +public Response uploadImage(Request request) { |
| 210 | + // Get file from request |
| 211 | + UploadedFile file = request.file("image"); |
| 212 | + |
| 213 | + if (file == null) { |
| 214 | + return response().json( |
| 215 | + "status", "error", |
| 216 | + "message", "No image file uploaded" |
| 217 | + ).status(400); |
| 218 | + } |
| 219 | + |
| 220 | + // Validate file type |
| 221 | + if (!file.getContentType().startsWith("image/")) { |
| 222 | + return response().json( |
| 223 | + "status", "error", |
| 224 | + "message", "Uploaded file is not an image" |
| 225 | + ).status(400); |
| 226 | + } |
| 227 | + |
| 228 | + // Save file to disk |
| 229 | + String filename = System.currentTimeMillis() + "_" + file.getFilename(); |
| 230 | + String storagePath = "uploads/" + filename; |
| 231 | + |
| 232 | + try { |
| 233 | + file.saveAs(storagePath); |
| 234 | + } catch (IOException e) { |
| 235 | + return response().json( |
| 236 | + "status", "error", |
| 237 | + "message", "Failed to save uploaded file" |
| 238 | + ).status(500); |
| 239 | + } |
| 240 | + |
| 241 | + // Return success response |
| 242 | + return response().json( |
| 243 | + "status", "success", |
| 244 | + "message", "File uploaded successfully", |
| 245 | + "filename", filename, |
| 246 | + "path", storagePath, |
| 247 | + "size", file.getSize(), |
| 248 | + "contentType", file.getContentType() |
| 249 | + ); |
| 250 | +} |
| 251 | +``` |
| 252 | + |
| 253 | +## Authentication Middleware Example |
| 254 | + |
| 255 | +Here's how to implement a simple authentication middleware: |
| 256 | + |
| 257 | +```java |
| 258 | +import jazzyframework.http.middleware.Middleware; |
| 259 | + |
| 260 | +public class AuthMiddleware implements Middleware { |
| 261 | + |
| 262 | + @Override |
| 263 | + public Response handle(Request request, MiddlewareChain chain) { |
| 264 | + // Get authorization header |
| 265 | + String token = request.header("Authorization"); |
| 266 | + |
| 267 | + if (token == null || !token.startsWith("Bearer ")) { |
| 268 | + return response().json( |
| 269 | + "status", "error", |
| 270 | + "message", "Unauthorized" |
| 271 | + ).status(401); |
| 272 | + } |
| 273 | + |
| 274 | + // Extract token value |
| 275 | + token = token.substring(7); |
| 276 | + |
| 277 | + try { |
| 278 | + // Verify token and get user (example) |
| 279 | + User user = TokenService.verifyToken(token); |
| 280 | + |
| 281 | + // Add user to request for later use in controllers |
| 282 | + request.setAttribute("user", user); |
| 283 | + |
| 284 | + // Continue to next middleware or controller |
| 285 | + return chain.next(request); |
| 286 | + |
| 287 | + } catch (Exception e) { |
| 288 | + return response().json( |
| 289 | + "status", "error", |
| 290 | + "message", "Invalid or expired token" |
| 291 | + ).status(401); |
| 292 | + } |
| 293 | + } |
| 294 | +} |
| 295 | + |
| 296 | +// Apply middleware to specific routes |
| 297 | +router.get("/api/profile", profileController::getProfile).with(new AuthMiddleware()); |
| 298 | +router.group("/api/admin", adminRoutes -> { |
| 299 | + adminRoutes.get("/users", adminController::getUsers); |
| 300 | + adminRoutes.post("/settings", adminController::updateSettings); |
| 301 | +}).with(new AuthMiddleware()); |
| 302 | +``` |
| 303 | + |
| 304 | +## Next Steps |
| 305 | + |
| 306 | +For more information on specific components: |
| 307 | + |
| 308 | +- [Getting Started](getting-started.md) |
| 309 | +- [Routing](routing.md) |
| 310 | +- [Requests](requests.md) |
| 311 | +- [Responses](responses.md) |
| 312 | +- [Validation](validation.md) |
| 313 | +- [JSON Operations](json.md) |
0 commit comments