rapitapir 0.1.2 โ†’ 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +7 -7
  3. data/.rubocop_todo.yml +88 -0
  4. data/CHANGELOG.md +29 -1
  5. data/README.md +1339 -236
  6. data/RUBY_WEEKLY_LAUNCH_POST.md +200 -0
  7. data/docs/RAILS_INTEGRATION_IMPLEMENTATION.md +209 -0
  8. data/docs/SINATRA_EXTENSION.md +399 -348
  9. data/docs/STRICT_VALIDATION.md +229 -0
  10. data/docs/VALIDATION_IMPROVEMENTS.md +218 -0
  11. data/docs/adr/0001-base-class-strategy.md +33 -0
  12. data/docs/adr/0002-type-shortcut-and-type-system.md +30 -0
  13. data/docs/adr/0003-openapi-source-of-truth.md +32 -0
  14. data/docs/adr/0004-client-generation-typescript-first.md +34 -0
  15. data/docs/adr/0005-auth-architecture.md +32 -0
  16. data/docs/adr/0006-observability-defaults.md +30 -0
  17. data/docs/adr/0007-ai-scope-and-boundaries.md +30 -0
  18. data/docs/adr/README.md +46 -0
  19. data/docs/adr/template.md +24 -0
  20. data/docs/ai-integration-plan.md +112 -0
  21. data/docs/auto-derivation.md +505 -92
  22. data/docs/blueprint.md +92 -4
  23. data/docs/endpoint-definition.md +536 -129
  24. data/docs/implementation-status.md +1 -1
  25. data/docs/n8n-integration.md +212 -0
  26. data/docs/observability.md +810 -500
  27. data/docs/using-mcp.md +93 -0
  28. data/examples/ai/knowledge_base_rag.rb +83 -0
  29. data/examples/ai/user_management_mcp.rb +92 -0
  30. data/examples/ai/user_validation_llm.rb +187 -0
  31. data/examples/auto_derivation_ruby_friendly.rb +44 -113
  32. data/examples/cli/user_api_endpoints.rb +63 -36
  33. data/examples/demo_api.rb +57 -18
  34. data/examples/enterprise_extension_demo.rb +13 -13
  35. data/examples/enterprise_rapitapir_api.rb +81 -93
  36. data/examples/nocodb/nocodb_scaffold/Gemfile +22 -0
  37. data/examples/nocodb/nocodb_scaffold/README.md +10 -0
  38. data/examples/nocodb/nocodb_scaffold/Rakefile +7 -0
  39. data/examples/nocodb/nocodb_scaffold/app/api/app.rb +1139 -0
  40. data/examples/nocodb/nocodb_scaffold/app/models/email_template.rb +6 -0
  41. data/examples/nocodb/nocodb_scaffold/app/models/faq.rb +6 -0
  42. data/examples/nocodb/nocodb_scaffold/app/models/feature.rb +6 -0
  43. data/examples/nocodb/nocodb_scaffold/app/models/idea.rb +6 -0
  44. data/examples/nocodb/nocodb_scaffold/app/models/itinerary_day.rb +6 -0
  45. data/examples/nocodb/nocodb_scaffold/app/models/route.rb +6 -0
  46. data/examples/nocodb/nocodb_scaffold/app/models/subscriber.rb +6 -0
  47. data/examples/nocodb/nocodb_scaffold/app/models/tour.rb +6 -0
  48. data/examples/nocodb/nocodb_scaffold/app/models/webhook.rb +6 -0
  49. data/examples/nocodb/nocodb_scaffold/app/models_loader.rb +3 -0
  50. data/examples/nocodb/nocodb_scaffold/config/database.yml +11 -0
  51. data/examples/nocodb/nocodb_scaffold/config.ru +9 -0
  52. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152012_create_features.rb +10 -0
  53. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152013_create_tours.rb +10 -0
  54. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152014_create_routes.rb +10 -0
  55. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152015_create_itinerary_days.rb +10 -0
  56. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152016_create_subscribers.rb +10 -0
  57. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152017_create_email_templates.rb +10 -0
  58. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152018_create_faqs.rb +10 -0
  59. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152019_create_webhooks.rb +10 -0
  60. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152020_create_ideas.rb +10 -0
  61. data/examples/nocodb/swagger.json +4378 -0
  62. data/examples/production_ready_example.rb +78 -58
  63. data/examples/rails/RAILS_8_GUIDE.md +165 -0
  64. data/examples/rails/RAILS_LOADING_FIX.rb +35 -0
  65. data/examples/rails/README.md +497 -0
  66. data/examples/rails/comprehensive_test.rb +91 -0
  67. data/examples/rails/config/routes.rb +48 -0
  68. data/examples/rails/debug_controller.rb +63 -0
  69. data/examples/rails/detailed_test.rb +46 -0
  70. data/examples/rails/enhanced_users_controller.rb +278 -0
  71. data/examples/rails/final_server_test.rb +50 -0
  72. data/examples/rails/hello_world_app.rb +116 -0
  73. data/examples/rails/hello_world_controller.rb +186 -0
  74. data/examples/rails/hello_world_routes.rb +28 -0
  75. data/examples/rails/rails8_minimal_demo.rb +132 -0
  76. data/examples/rails/rails8_simple_demo.rb +140 -0
  77. data/examples/rails/rails8_working_demo.rb +255 -0
  78. data/examples/rails/real_world_blog_api.rb +510 -0
  79. data/examples/rails/server_test.rb +46 -0
  80. data/examples/rails/test_direct_processing.rb +41 -0
  81. data/examples/rails/test_hello_world.rb +80 -0
  82. data/examples/rails/test_rails_integration.rb +54 -0
  83. data/examples/rails/traditional_app/Gemfile +37 -0
  84. data/examples/rails/traditional_app/README.md +265 -0
  85. data/examples/rails/traditional_app/app/controllers/api/v1/posts_controller.rb +254 -0
  86. data/examples/rails/traditional_app/app/controllers/api/v1/users_controller.rb +220 -0
  87. data/examples/rails/traditional_app/app/controllers/application_controller.rb +86 -0
  88. data/examples/rails/traditional_app/app/controllers/application_controller_simplified.rb +87 -0
  89. data/examples/rails/traditional_app/app/controllers/documentation_controller.rb +149 -0
  90. data/examples/rails/traditional_app/app/controllers/health_controller.rb +42 -0
  91. data/examples/rails/traditional_app/config/routes.rb +25 -0
  92. data/examples/rails/traditional_app/config/routes_best_practice.rb +25 -0
  93. data/examples/rails/traditional_app/config/routes_simplified.rb +36 -0
  94. data/examples/rails/traditional_app_runnable.rb +406 -0
  95. data/examples/rails/users_controller.rb +4 -1
  96. data/examples/serverless/Gemfile +43 -0
  97. data/examples/serverless/QUICKSTART.md +331 -0
  98. data/examples/serverless/README.md +520 -0
  99. data/examples/serverless/aws_lambda_example.rb +307 -0
  100. data/examples/serverless/aws_sam_template.yaml +215 -0
  101. data/examples/serverless/azure_functions_example.rb +407 -0
  102. data/examples/serverless/deploy.rb +204 -0
  103. data/examples/serverless/gcp_cloud_functions_example.rb +367 -0
  104. data/examples/serverless/gcp_function.yaml +23 -0
  105. data/examples/serverless/host.json +24 -0
  106. data/examples/serverless/package.json +32 -0
  107. data/examples/serverless/spec/aws_lambda_spec.rb +196 -0
  108. data/examples/serverless/spec/spec_helper.rb +89 -0
  109. data/examples/serverless/vercel.json +31 -0
  110. data/examples/serverless/vercel_example.rb +404 -0
  111. data/examples/simple_demo_api.rb +40 -7
  112. data/examples/strict_validation_examples.rb +104 -0
  113. data/examples/user_api.rb +130 -132
  114. data/examples/validation_error_examples.rb +173 -0
  115. data/lib/rapitapir/ai/llm_instruction.rb +456 -0
  116. data/lib/rapitapir/ai/mcp.rb +134 -0
  117. data/lib/rapitapir/ai/rag.rb +287 -0
  118. data/lib/rapitapir/ai/rag_middleware.rb +147 -0
  119. data/lib/rapitapir/auth/oauth2.rb +44 -58
  120. data/lib/rapitapir/cli/command.rb +392 -6
  121. data/lib/rapitapir/cli/mcp_export.rb +18 -0
  122. data/lib/rapitapir/cli/scaffold_generator.rb +639 -0
  123. data/lib/rapitapir/cli/validator.rb +3 -7
  124. data/lib/rapitapir/core/endpoint.rb +59 -6
  125. data/lib/rapitapir/core/enhanced_endpoint.rb +3 -7
  126. data/lib/rapitapir/dsl/enhanced_structures.rb +1 -1
  127. data/lib/rapitapir/dsl/fluent_endpoint_builder.rb +53 -0
  128. data/lib/rapitapir/endpoint_registry.rb +47 -0
  129. data/lib/rapitapir/observability/health_check.rb +4 -4
  130. data/lib/rapitapir/observability/logging.rb +10 -10
  131. data/lib/rapitapir/openapi/schema_generator.rb +46 -2
  132. data/lib/rapitapir/schema.rb +2 -2
  133. data/lib/rapitapir/server/enhanced_rack_adapter.rb +11 -8
  134. data/lib/rapitapir/server/middleware.rb +2 -2
  135. data/lib/rapitapir/server/rack_adapter.rb +1 -3
  136. data/lib/rapitapir/server/rails/configuration.rb +77 -0
  137. data/lib/rapitapir/server/rails/controller_base.rb +185 -0
  138. data/lib/rapitapir/server/rails/documentation_helpers.rb +76 -0
  139. data/lib/rapitapir/server/rails/resource_builder.rb +181 -0
  140. data/lib/rapitapir/server/rails/routes.rb +114 -0
  141. data/lib/rapitapir/server/rails_adapter.rb +10 -3
  142. data/lib/rapitapir/server/rails_adapter_class.rb +1 -3
  143. data/lib/rapitapir/server/rails_controller.rb +1 -3
  144. data/lib/rapitapir/server/rails_integration.rb +67 -0
  145. data/lib/rapitapir/server/rails_response_handler.rb +16 -3
  146. data/lib/rapitapir/server/sinatra_adapter.rb +29 -5
  147. data/lib/rapitapir/server/sinatra_integration.rb +4 -4
  148. data/lib/rapitapir/sinatra/extension.rb +2 -2
  149. data/lib/rapitapir/sinatra/oauth2_helpers.rb +34 -40
  150. data/lib/rapitapir/types/array.rb +4 -0
  151. data/lib/rapitapir/types/auto_derivation.rb +4 -20
  152. data/lib/rapitapir/types/datetime.rb +1 -3
  153. data/lib/rapitapir/types/float.rb +2 -6
  154. data/lib/rapitapir/types/hash.rb +40 -2
  155. data/lib/rapitapir/types/integer.rb +4 -12
  156. data/lib/rapitapir/types/object.rb +6 -2
  157. data/lib/rapitapir/types.rb +6 -2
  158. data/lib/rapitapir/version.rb +1 -1
  159. data/lib/rapitapir.rb +5 -3
  160. data/rapitapir.gemspec +3 -2
  161. metadata +142 -8
data/README.md CHANGED
@@ -1,278 +1,825 @@
1
- # RapiTapir## ๐Ÿ†• What's New
1
+ # RapiTapir
2
2
 
3
- - **โœจ - **๐Ÿ“ Type Shortcuts**: Global `T.string`, `T.integer`, etc. (automatically available!)
4
- - **๐Ÿ”„ GitHub Pages**: Modern documentation deployment with GitHub Actionsean Base Class**: `class MyAPI < SinatraRapiTapir` - the simplest way to create APIs
5
- - **๐ŸŽฏ Enhanced HTTP DSL**: Built-in GET, POST, PUT, DELETE methods with fluent chaining
6
- - **๐Ÿ”ง Zero Boilerplate**: Automatic extension registration and feature setup
7
- - ๐Ÿ“ **Type Shortcuts**: Clean syntax with global `T` constant (automatic - no setup needed!)
8
- - **๐Ÿ“š GitHub Pages Ready**: Modern documentation deployment with GitHub Actions
9
- - **๐Ÿงช Comprehensive Tests**: 470 tests passing with 70% coverage modern Ruby library for building type-safe HTTP APIs with automatic OpenAPI documentation**
10
-
11
- [![Tests](https://img.shields.io/badge/tests-470%20passing-brightgreen)](spec/)
12
- [![Coverage](https://img.shields.io/badge/coverage-70.13%25-green)](coverage/)
13
- [![Ruby](https://img.shields.io/badge/ruby-3.1%2B-red)](Gemfile)
3
+ [![Tests](https://img.shields.io/badge/tests-695%20passing-brightgreen)](spec/)
4
+ [![Coverage](https://img.shields.io/badge/coverage-72.7%25-green)](coverage/)
5
+ [![Branches](https://img.shields.io/badge/branches-44.89%25-yellow)](coverage/)
6
+ [![Ruby](https://img.shields.io/badge/ruby-3.3%2B-red)](Gemfile)
14
7
  [![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
8
+ [![RuboCop](https://img.shields.io/badge/code%20style-rubocop-brightgreen)](https://github.com/rubocop/rubocop)
9
+ [![AI Ready](https://img.shields.io/badge/AI-LLM%20%7C%20RAG%20%7C%20MCP-purple)](lib/rapitapir/ai/)
15
10
 
16
- **RapiTapir ๐Ÿฆ™** combines the expressiveness of Ruby with the safety of strong typing to create APIs that are both powerful and reliable. Define your endpoints once with our fluent DSL, and get automatic validation, documentation, and client generation.
11
+ **RapiTapir ๐Ÿฆ™** combines the expressiveness of Ruby with the safety of strong typing to create APIs that are both powerful and reliable. Define your endpoints once with our fluent DSL, and get automatic validation, documentation, client generation, and AI-powered features.
17
12
 
18
- ## ๐Ÿ†• What's New
13
+ ## ๐Ÿš€ Latest Features (v2.0)
19
14
 
20
- - **โœจ Clean Base Class**: `class MyAPI < SinatraRapiTapir` - the simplest way to create APIs
21
- - **๐ŸŽฏ Enhanced HTTP DSL**: Built-in GET, POST, PUT, DELETE methods with fluent chaining
22
- - **๐Ÿ”ง Zero Boilerplate**: Automatic extension registration and feature setup
23
- - **๏ฟฝ Type Shortcuts**: Use `T.string` instead of `RapiTapir::Types.string` for cleaner code
24
- - **๏ฟฝ๐Ÿ“š GitHub Pages Ready**: Modern documentation deployment with GitHub Actions
25
- - **๐Ÿงช Comprehensive Tests**: 470 tests passing with 70% coverage
15
+ - **๐Ÿค– AI Integration**: Built-in LLM instruction generation, RAG pipelines, and MCP export
16
+ - **โœจ SinatraRapiTapir Base Class**: `class MyAPI < SinatraRapiTapir` - zero-boilerplate API creation
17
+ - **๐ŸŽฏ Enhanced HTTP DSL**: Native GET, POST, PUT, DELETE methods with fluent chaining
18
+ - **๐Ÿ”ง Zero Configuration**: Automatic extension registration and intelligent defaults
19
+ - **โšก T Shortcut**: Use `T.string` instead of `RapiTapir::Types.string` everywhere
20
+ - **๐Ÿ“š GitHub Pages Ready**: Modern documentation deployment with GitHub Actions
21
+ - **๐Ÿ” CLI Toolkit**: Complete command-line interface for generation, validation, and serving
22
+ - **๐Ÿงช Comprehensive Tests**: 695 examples, 0 failures; 72.7% coverage
26
23
 
27
24
  ## โœจ Why RapiTapir?
28
25
 
29
- - **๐Ÿ”’ Type Safety**: Strong typing for inputs and outputs with runtime validation
26
+ - **๐Ÿ”’ Type Safety**: Strong typing with runtime validation and compile-time confidence
30
27
  - **๐Ÿ“– Auto Documentation**: OpenAPI 3.0 specs generated automatically from your code
31
28
  - **๐Ÿš€ Framework Agnostic**: Works with Sinatra, Rails, and any Rack-based framework
32
29
  - **๐Ÿ›ก๏ธ Production Ready**: Built-in security, observability, and authentication features
33
30
  - **๐Ÿ’Ž Ruby Native**: Designed specifically for Ruby developers who love clean, readable code
34
31
  - **๐Ÿ”ง Zero Config**: Get started in minutes with sensible defaults
35
- - **โœจ Clean Syntax**: Elegant base class: `class MyAPI < SinatraRapiTapir`
36
- - **๐ŸŽฏ Enhanced DSL**: Built-in HTTP verb methods (GET, POST, PUT, etc.)
37
- - **๏ฟฝ Type Shortcuts**: Clean type syntax with `T.string`, `T.integer`, etc.
38
- - **๏ฟฝ๐Ÿ”„ GitHub Pages**: Modern documentation deployment with GitHub Actions
32
+ - **๐Ÿค– AI Powered**: Built-in LLM instruction generation, RAG pipelines, and MCP export
33
+ - **โšก Enhanced DSL**: Clean syntax with `T.string`, HTTP verbs, and resource builders
34
+ - **๐Ÿ”„ CLI Toolkit**: Complete command-line interface for all development tasks
39
35
 
40
36
  ## ๐Ÿš€ Quick Start
41
37
 
42
- ### Installation
43
-
44
- Add to your Gemfile:
38
+ ### Minimal Example (30 seconds)
45
39
 
46
40
  ```ruby
47
- gem 'rapitapir'
41
+ require 'rapitapir'
42
+
43
+ class HelloAPI < SinatraRapiTapir
44
+ # That's it! Zero configuration needed.
45
+ endpoint(
46
+ GET('/hello')
47
+ .query(:name, T.string, description: 'Your name')
48
+ .ok(T.hash({ "message" => T.string }))
49
+ .build
50
+ ) { |inputs| { message: "Hello, #{inputs[:name]}!" } }
51
+
52
+ run! if __FILE__ == $0
53
+ end
48
54
  ```
49
55
 
50
- ### Basic Sinatra Example
56
+ **Start server**: `ruby hello_api.rb`
57
+ **Try it**: `curl "http://localhost:4567/hello?name=World"`
58
+ **Docs**: `http://localhost:4567/docs`
59
+
60
+ ### Complete Example (5 minutes)
51
61
 
52
62
  ```ruby
53
- require 'rapitapir' # Only one require needed!
63
+ require 'rapitapir'
54
64
 
55
65
  class BookAPI < SinatraRapiTapir
56
66
  # Configure API information
57
67
  rapitapir do
58
68
  info(
59
- title: 'Book API',
60
- description: 'A simple book management API',
61
- version: '1.0.0'
69
+ title: 'Book Management API',
70
+ description: 'A comprehensive book management system with AI features',
71
+ version: '2.0.0'
62
72
  )
63
- development_defaults! # Auto CORS, docs, health checks
73
+ development_defaults! # Auto CORS, docs, health checks, metrics
64
74
  end
65
75
 
66
- # Define your data schema with T shortcut (globally available!)
76
+ # Define schemas using T shortcut (available everywhere!)
67
77
  BOOK_SCHEMA = T.hash({
68
78
  "id" => T.integer,
69
79
  "title" => T.string(min_length: 1, max_length: 255),
70
80
  "author" => T.string(min_length: 1),
71
81
  "published" => T.boolean,
72
- "isbn" => T.optional(T.string),
73
- "pages" => T.optional(T.integer(minimum: 1))
82
+ "isbn" => T.optional(T.string(pattern: /^\d{13}$/)),
83
+ "pages" => T.optional(T.integer(minimum: 1)),
84
+ "tags" => T.optional(T.array(T.string)),
85
+ "metadata" => T.optional(T.hash({
86
+ "genre" => T.string,
87
+ "rating" => T.float(minimum: 0, maximum: 5)
88
+ }))
74
89
  })
75
90
 
76
- # Define endpoints with the elegant resource DSL and enhanced HTTP verbs
91
+ # RESTful resource with full CRUD
77
92
  api_resource '/books', schema: BOOK_SCHEMA do
78
93
  crud do
79
- index { Book.all }
80
-
81
- show do |inputs|
82
- Book.find(inputs[:id]) || halt(404, { error: 'Book not found' }.to_json)
94
+ index do
95
+ # Automatic pagination and filtering
96
+ books = Book.all
97
+ books = books.where(published: true) if params[:published] == 'true'
98
+ books.limit(params[:limit] || 50).map(&:to_h)
83
99
  end
84
100
 
101
+ show { |inputs| Book.find(inputs[:id])&.to_h || halt(404) }
102
+
85
103
  create do |inputs|
86
- Book.create(inputs[:body])
104
+ book = Book.create(inputs[:body])
105
+ status 201
106
+ book.to_h
87
107
  end
108
+
109
+ update { |inputs| Book.update(inputs[:id], inputs[:body]).to_h }
110
+ destroy { |inputs| Book.delete(inputs[:id]); status 204 }
88
111
  end
89
112
 
90
- # Custom endpoint using enhanced DSL
113
+ # Custom endpoints with full type safety
91
114
  custom :get, 'featured' do
92
- Book.where(featured: true)
115
+ Book.where(featured: true).map(&:to_h)
116
+ end
117
+
118
+ custom :post, ':id/reviews' do |inputs|
119
+ book = Book.find(inputs[:id])
120
+ review = book.add_review(inputs[:body])
121
+ status 201
122
+ review.to_h
93
123
  end
94
124
  end
95
125
 
96
- # Alternative endpoint definition using enhanced HTTP verb DSL
126
+ # Advanced search with AI-powered features
97
127
  endpoint(
98
128
  GET('/books/search')
99
129
  .query(:q, T.string(min_length: 1), description: 'Search query')
100
130
  .query(:limit, T.optional(T.integer(minimum: 1, maximum: 100)), description: 'Results limit')
101
- .summary('Search books')
102
- .description('Search books by title or author')
103
- .tags('Search')
104
- .ok(T.array(BOOK_SCHEMA))
105
- .bad_request(T.hash({ "error" => T.string }), description: 'Invalid search parameters')
131
+ .query(:ai_powered, T.optional(T.boolean), description: 'Use AI-enhanced search')
132
+ .summary('Search books with optional AI enhancement')
133
+ .description('Search books by title, author, or content with optional AI semantic search')
134
+ .tags('Search', 'AI')
135
+ .ok(T.hash({
136
+ "books" => T.array(BOOK_SCHEMA),
137
+ "total" => T.integer,
138
+ "ai_enhanced" => T.boolean,
139
+ "suggestions" => T.optional(T.array(T.string))
140
+ }))
141
+ .bad_request(T.hash({ "error" => T.string }))
142
+ .enable_rag # AI-powered retrieval augmented generation
143
+ .enable_mcp # Export to Model Context Protocol
106
144
  .build
107
145
  ) do |inputs|
108
146
  query = inputs[:q]
109
147
  limit = inputs[:limit] || 20
148
+ ai_powered = inputs[:ai_powered] || false
149
+
150
+ if ai_powered
151
+ # Use AI-enhanced search
152
+ results = BookSearchService.ai_search(query, limit: limit)
153
+ suggestions = BookSearchService.get_suggestions(query)
154
+ else
155
+ results = Book.search(query).limit(limit)
156
+ suggestions = nil
157
+ end
158
+
159
+ {
160
+ books: results.map(&:to_h),
161
+ total: results.count,
162
+ ai_enhanced: ai_powered,
163
+ suggestions: suggestions
164
+ }
165
+ end
166
+
167
+ run! if __FILE__ == $0
168
+ end
169
+ ```
170
+
171
+ **Start and explore**:
172
+ - **Server**: `ruby book_api.rb`
173
+ - **Interactive Docs**: `http://localhost:4567/docs`
174
+ - **OpenAPI Spec**: `http://localhost:4567/openapi.json`
175
+ - **Health Check**: `http://localhost:4567/health`
176
+ ## ๐Ÿ—๏ธ Advanced Features
177
+
178
+ ### ๐Ÿค– AI-Powered APIs
179
+
180
+ ```ruby
181
+ class AIBookAPI < SinatraRapiTapir
182
+ rapitapir do
183
+ info(title: 'AI-Powered Book API', version: '2.0.0')
184
+ development_defaults!
185
+ end
186
+
187
+ # Configure AI providers
188
+ configure do
189
+ set :openai_api_key, ENV['OPENAI_API_KEY']
190
+ set :rag_backend, :memory # or :elasticsearch, :postgresql
191
+ end
192
+
193
+ # AI-enhanced book recommendations
194
+ endpoint(
195
+ GET('/books/recommendations')
196
+ .query(:user_id, T.integer, description: 'User ID for personalization')
197
+ .query(:preferences, T.optional(T.string), description: 'User preferences text')
198
+ .summary('Get AI-powered book recommendations')
199
+ .description('Uses LLM to generate personalized book recommendations')
200
+ .tags('AI', 'Recommendations')
201
+ .ok(T.hash({
202
+ "recommendations" => T.array(BOOK_SCHEMA),
203
+ "reasoning" => T.string,
204
+ "confidence" => T.float(minimum: 0, maximum: 1)
205
+ }))
206
+ .enable_llm_instructions(purpose: :completion) # Generate LLM instructions
207
+ .enable_rag(
208
+ retrieval_backend: :memory,
209
+ llm_provider: :openai,
210
+ context_window: 4000
211
+ )
212
+ .enable_mcp # Export for AI agent consumption
213
+ .build
214
+ ) do |inputs|
215
+ user = User.find(inputs[:user_id])
216
+ preferences = inputs[:preferences] || user.inferred_preferences
217
+
218
+ # RAG pipeline automatically injects relevant context
219
+ recommendations = AIRecommendationService.generate(
220
+ user: user,
221
+ preferences: preferences,
222
+ context: rag_context # Automatically provided by RAG middleware
223
+ )
224
+
225
+ {
226
+ recommendations: recommendations[:books],
227
+ reasoning: recommendations[:explanation],
228
+ confidence: recommendations[:confidence_score]
229
+ }
230
+ end
231
+
232
+ # LLM instruction generation endpoint
233
+ endpoint(
234
+ GET('/ai/instructions')
235
+ .query(:endpoint_id, T.string, description: 'Endpoint ID to generate instructions for')
236
+ .query(:purpose, T.string(enum: %w[validation transformation analysis documentation testing completion]),
237
+ description: 'Instruction purpose')
238
+ .summary('Generate LLM instructions for endpoints')
239
+ .ok(T.hash({
240
+ "instructions" => T.string,
241
+ "metadata" => T.hash({
242
+ "endpoint" => T.string,
243
+ "purpose" => T.string,
244
+ "generated_at" => T.datetime
245
+ })
246
+ }))
247
+ .build
248
+ ) do |inputs|
249
+ generator = RapiTapir::AI::LLMInstruction::Generator.new
250
+ endpoint = find_endpoint(inputs[:endpoint_id])
251
+
252
+ instructions = generator.generate_instructions(
253
+ endpoint: endpoint,
254
+ purpose: inputs[:purpose].to_sym
255
+ )
256
+
257
+ {
258
+ instructions: instructions,
259
+ metadata: {
260
+ endpoint: endpoint.summary || endpoint.path,
261
+ purpose: inputs[:purpose],
262
+ generated_at: Time.now
263
+ }
264
+ }
265
+ end
266
+
267
+ # Export Model Context Protocol (MCP) for AI agents
268
+ endpoint(
269
+ GET('/mcp/export')
270
+ .summary('Export API for AI agent consumption')
271
+ .description('Generates MCP-compatible JSON for AI agents and development tools')
272
+ .tags('AI', 'MCP', 'Developer Tools')
273
+ .ok(T.hash({
274
+ "service" => T.hash({
275
+ "name" => T.string,
276
+ "version" => T.string,
277
+ "description" => T.string
278
+ }),
279
+ "endpoints" => T.array(T.hash({
280
+ "id" => T.string,
281
+ "method" => T.string,
282
+ "path" => T.string,
283
+ "summary" => T.string,
284
+ "input_schema" => T.hash({}),
285
+ "output_schema" => T.hash({})
286
+ })),
287
+ "generated_at" => T.datetime
288
+ }))
289
+ .build
290
+ ) do
291
+ exporter = RapiTapir::AI::MCP::Exporter.new(rapitapir_endpoints)
292
+ JSON.parse(exporter.export_json(pretty: true))
293
+ end
294
+
295
+ run! if __FILE__ == $0
296
+ end
297
+ ```
298
+
299
+ ### ๐Ÿ” OAuth2 + Auth0 Integration
300
+
301
+ ```ruby
302
+ class SecureAPI < SinatraRapiTapir
303
+ rapitapir do
304
+ info(title: 'Secure API with Auth0', version: '2.0.0')
305
+
306
+ # Configure Auth0 OAuth2
307
+ oauth2_auth0 :auth0,
308
+ domain: ENV['AUTH0_DOMAIN'],
309
+ audience: ENV['AUTH0_AUDIENCE'],
310
+ realm: 'API Access'
311
+
312
+ production_defaults! # Security headers, rate limiting, etc.
313
+ end
314
+
315
+ # Public endpoints
316
+ endpoint(
317
+ GET('/public/status')
318
+ .summary('Public API status')
319
+ .ok(T.hash({
320
+ "status" => T.string,
321
+ "version" => T.string,
322
+ "authenticated" => T.boolean
323
+ }))
324
+ .build
325
+ ) do
326
+ {
327
+ status: 'operational',
328
+ version: '2.0.0',
329
+ authenticated: authenticated?
330
+ }
331
+ end
332
+
333
+ # Protected endpoints with scope requirements
334
+ endpoint(
335
+ GET('/users/profile')
336
+ .summary('Get current user profile')
337
+ .description('Requires valid Auth0 token with read:profile scope')
338
+ .bearer_auth(scopes: ['read:profile'])
339
+ .tags('Users', 'Profile')
340
+ .ok(T.hash({
341
+ "user" => T.hash({
342
+ "id" => T.string,
343
+ "email" => T.string,
344
+ "name" => T.string,
345
+ "roles" => T.array(T.string),
346
+ "permissions" => T.array(T.string)
347
+ }),
348
+ "metadata" => T.hash({
349
+ "last_login" => T.datetime,
350
+ "login_count" => T.integer
351
+ })
352
+ }))
353
+ .error_response(401, T.hash({ "error" => T.string }), description: 'Unauthorized')
354
+ .error_response(403, T.hash({ "error" => T.string }), description: 'Insufficient permissions')
355
+ .build
356
+ ) do |inputs|
357
+ # Current user automatically available from Auth0 context
358
+ user_info = current_auth_context[:user_info]
359
+
360
+ {
361
+ user: {
362
+ id: user_info['sub'],
363
+ email: user_info['email'],
364
+ name: user_info['name'],
365
+ roles: user_info['roles'] || [],
366
+ permissions: current_auth_context[:permissions] || []
367
+ },
368
+ metadata: {
369
+ last_login: Time.parse(user_info['updated_at']),
370
+ login_count: user_info['logins_count'] || 0
371
+ }
372
+ }
373
+ end
374
+
375
+ # Admin-only endpoints
376
+ endpoint(
377
+ DELETE('/admin/users/:user_id')
378
+ .summary('Delete user (admin only)')
379
+ .path_param(:user_id, T.string, description: 'User ID to delete')
380
+ .bearer_auth(scopes: ['delete:users', 'admin'])
381
+ .tags('Admin', 'Users')
382
+ .ok(T.hash({ "message" => T.string, "deleted_user_id" => T.string }))
383
+ .error_response(401, T.hash({ "error" => T.string }))
384
+ .error_response(403, T.hash({ "error" => T.string }))
385
+ .error_response(404, T.hash({ "error" => T.string }))
386
+ .build
387
+ ) do |inputs|
388
+ # Verify admin scope
389
+ require_scope!('admin')
390
+
391
+ user_id = inputs[:user_id]
392
+ deleted_user = UserService.delete(user_id)
393
+
394
+ halt 404, { error: 'User not found' }.to_json unless deleted_user
110
395
 
111
- books = Book.search(query).limit(limit)
112
- books.map(&:to_h)
396
+ {
397
+ message: 'User successfully deleted',
398
+ deleted_user_id: user_id
399
+ }
400
+ end
401
+
402
+ # Scope-based middleware protection
403
+ protect_with_oauth2 scopes: ['api:access'] do
404
+ # All endpoints in this block require the api:access scope
405
+
406
+ endpoint(
407
+ GET('/protected/data')
408
+ .summary('Get protected data')
409
+ .ok(T.array(T.hash({ "id" => T.integer, "data" => T.string })))
410
+ .build
411
+ ) { ProtectedData.all.map(&:to_h) }
412
+ end
413
+
414
+ run! if __FILE__ == $0
415
+ end
416
+ ```
417
+
418
+ ### ๐Ÿ“Š Production Observability (OpenTelemetry + Honeycomb)
419
+
420
+ ```ruby
421
+ class MonitoredAPI < SinatraRapiTapir
422
+ rapitapir do
423
+ info(title: 'Production API with Full Observability', version: '2.0.0')
424
+
425
+ # Configure comprehensive observability
426
+ enable_observability do |config|
427
+ # Health checks with custom checks
428
+ config.health_checks.enable(path: '/health')
429
+ config.health_checks.add_check('database') { DatabaseHealthCheck.new }
430
+ config.health_checks.add_check('redis') { RedisHealthCheck.new }
431
+ config.health_checks.add_check('external_api') { ExternalAPIHealthCheck.new }
432
+
433
+ # OpenTelemetry tracing
434
+ config.tracing.enable_opentelemetry(
435
+ service_name: 'book-api',
436
+ service_version: '2.0.0',
437
+ environment: ENV['RAILS_ENV'] || 'development',
438
+ exporters: [:otlp, :honeycomb]
439
+ )
440
+
441
+ # Prometheus metrics
442
+ config.metrics.enable_prometheus(
443
+ namespace: 'book_api',
444
+ default_labels: {
445
+ service: 'book-api',
446
+ version: '2.0.0',
447
+ environment: ENV['RAILS_ENV'] || 'development'
448
+ }
449
+ )
450
+
451
+ # Structured logging
452
+ config.logging.enable_structured(
453
+ level: ENV['LOG_LEVEL'] || 'info',
454
+ format: :json,
455
+ additional_fields: {
456
+ service: 'book-api',
457
+ version: '2.0.0'
458
+ }
459
+ )
460
+ end
461
+
462
+ production_defaults!
463
+ end
464
+
465
+ # Monitored endpoint with custom metrics and tracing
466
+ endpoint(
467
+ GET('/books/:id')
468
+ .path_param(:id, T.integer, description: 'Book ID')
469
+ .query(:include, T.optional(T.array(T.string)), description: 'Related data to include')
470
+ .summary('Get book with full observability')
471
+ .description('Demonstrates comprehensive monitoring, tracing, and metrics')
472
+ .tags('Books', 'Monitoring')
473
+ .ok(BOOK_SCHEMA)
474
+ .error_response(404, T.hash({ "error" => T.string, "book_id" => T.integer }))
475
+ .error_response(500, T.hash({ "error" => T.string, "trace_id" => T.string }))
476
+ .with_metrics('book_requests', labels: { operation: 'get_by_id' })
477
+ .with_tracing('fetch_book', tags: { book_operation: 'get' })
478
+ .build
479
+ ) do |inputs|
480
+ book_id = inputs[:id]
481
+ includes = inputs[:include] || []
482
+
483
+ # Custom span for database operation
484
+ OpenTelemetry.tracer.in_span('database.book.find', attributes: { 'book.id' => book_id }) do |span|
485
+ start_time = Time.now
486
+
487
+ begin
488
+ book = Book.find(book_id)
489
+
490
+ # Record custom metrics
491
+ Prometheus.increment('book_lookups_total', labels: { found: 'true' })
492
+ Prometheus.observe('book_lookup_duration_seconds', Time.now - start_time)
493
+
494
+ # Add trace attributes
495
+ span.set_attribute('book.title', book.title)
496
+ span.set_attribute('book.author', book.author)
497
+ span.set_attribute('includes.count', includes.length)
498
+
499
+ halt 404, { error: 'Book not found', book_id: book_id }.to_json unless book
500
+
501
+ # Handle includes with additional tracing
502
+ if includes.any?
503
+ OpenTelemetry.tracer.in_span('book.load_includes') do |include_span|
504
+ include_span.set_attribute('includes', includes.join(','))
505
+ book = book.with_includes(includes)
506
+ end
507
+ end
508
+
509
+ # Log structured data
510
+ logger.info('Book retrieved successfully', {
511
+ book_id: book_id,
512
+ includes: includes,
513
+ duration_ms: ((Time.now - start_time) * 1000).round(2),
514
+ trace_id: span.context.trace_id.unpack1('H*')
515
+ })
516
+
517
+ book.to_h
518
+
519
+ rescue StandardError => e
520
+ # Record error metrics
521
+ Prometheus.increment('book_lookup_errors_total', labels: { error_type: e.class.name })
522
+
523
+ # Add error to span
524
+ span.record_exception(e)
525
+ span.status = OpenTelemetry::Trace::Status.error('Book lookup failed')
526
+
527
+ # Log error with context
528
+ logger.error('Book lookup failed', {
529
+ book_id: book_id,
530
+ error: e.message,
531
+ error_class: e.class.name,
532
+ trace_id: span.context.trace_id.unpack1('H*')
533
+ })
534
+
535
+ halt 500, {
536
+ error: 'Internal server error',
537
+ trace_id: span.context.trace_id.unpack1('H*')
538
+ }.to_json
539
+ end
540
+ end
541
+ end
542
+
543
+ # Performance monitoring endpoint
544
+ endpoint(
545
+ GET('/monitoring/performance')
546
+ .summary('Get API performance metrics')
547
+ .description('Returns real-time performance and health metrics')
548
+ .tags('Monitoring', 'Performance')
549
+ .bearer_auth(scopes: ['monitoring:read'])
550
+ .ok(T.hash({
551
+ "metrics" => T.hash({
552
+ "request_rate" => T.float,
553
+ "error_rate" => T.float,
554
+ "average_response_time" => T.float,
555
+ "p95_response_time" => T.float
556
+ }),
557
+ "health" => T.hash({
558
+ "overall_status" => T.string,
559
+ "checks" => T.hash({})
560
+ }),
561
+ "trace_sample" => T.optional(T.hash({
562
+ "trace_id" => T.string,
563
+ "span_count" => T.integer,
564
+ "duration_ms" => T.float
565
+ }))
566
+ }))
567
+ .build
568
+ ) do
569
+ {
570
+ metrics: {
571
+ request_rate: MetricsCollector.request_rate_per_second,
572
+ error_rate: MetricsCollector.error_rate_percentage,
573
+ average_response_time: MetricsCollector.average_response_time_ms,
574
+ p95_response_time: MetricsCollector.p95_response_time_ms
575
+ },
576
+ health: {
577
+ overall_status: HealthChecker.overall_status,
578
+ checks: HealthChecker.detailed_status
579
+ },
580
+ trace_sample: TracingCollector.recent_trace_sample
581
+ }
113
582
  end
114
583
 
115
584
  run! if __FILE__ == $0
116
585
  end
117
586
  ```
118
587
 
119
- Start your server and visit:
120
- - **๐Ÿ“– Interactive Documentation**: `http://localhost:4567/docs`
121
- - **๐Ÿ“‹ OpenAPI Specification**: `http://localhost:4567/openapi.json`
588
+ ### ๐Ÿ› ๏ธ CLI Development Toolkit
122
589
 
123
- That's it! You now have a fully documented, type-safe API with interactive documentation.
590
+ RapiTapir includes a comprehensive CLI for all development tasks:
591
+
592
+ ```bash
593
+ # Generate and validate
594
+ rapitapir generate openapi --output api-spec.json
595
+ rapitapir generate client typescript --output client/api.ts
596
+ rapitapir generate docs markdown --output API.md
597
+ rapitapir validate endpoints --file my_api.rb
598
+
599
+ # AI-powered features
600
+ rapitapir llm generate --endpoint-id "get_books" --purpose validation
601
+ rapitapir llm export --format instructions --output ai-prompts/
602
+ rapitapir mcp export --output mcp-context.json
603
+
604
+ # Development server
605
+ rapitapir serve --port 3000 --docs-path /documentation
606
+ rapitapir docs --serve --port 8080
607
+
608
+ # Project scaffolding
609
+ rapitapir new my-api --template sinatra-ai
610
+ rapitapir generate scaffold books --with-auth --with-ai
611
+ ```
124
612
 
125
613
  ## ๐Ÿ—๏ธ Core Features
126
614
 
127
- ### Clean Base Class Syntax
615
+ ### โœจ SinatraRapiTapir Base Class
128
616
 
129
- Create APIs with the cleanest possible syntax:
617
+ The cleanest way to create APIs with zero boilerplate:
130
618
 
131
619
  ```ruby
132
620
  require 'rapitapir'
133
621
 
134
622
  class MyAPI < SinatraRapiTapir
135
623
  rapitapir do
136
- info(title: 'My API', version: '1.0.0')
137
- development_defaults! # Auto CORS, docs, health checks
624
+ info(title: 'My API', version: '2.0.0')
625
+ development_defaults! # Auto CORS, docs, health checks, metrics
138
626
  end
139
627
 
140
- # Enhanced HTTP verb DSL automatically available + T shortcut for types
628
+ # Enhanced HTTP verb DSL + T shortcut automatically available
141
629
  endpoint(
142
- GET('/books')
143
- .summary('List all books')
144
- .ok(T.array(BOOK_SCHEMA))
145
- .error_response(500, T.hash({ "error" => T.string }))
630
+ GET('/items')
631
+ .summary('List all items')
632
+ .query(:filter, T.optional(T.string), description: 'Filter criteria')
633
+ .ok(T.array(T.hash({ "id" => T.integer, "name" => T.string })))
146
634
  .build
147
- ) { Book.all }
635
+ ) { |inputs| Item.filtered(inputs[:filter]).map(&:to_h) }
148
636
  end
149
637
  ```
150
638
 
151
- ### Type-Safe API Design
639
+ ### ๐Ÿ”’ Type-Safe API Design
152
640
 
153
- Define your data schemas once and use them everywhere:
641
+ Define schemas once, use everywhere with runtime validation:
154
642
 
155
643
  ```ruby
156
- # T shortcut is automatically available - no setup needed!
644
+ # T shortcut available globally - no imports needed!
157
645
  USER_SCHEMA = T.hash({
158
646
  "id" => T.integer,
159
647
  "name" => T.string(min_length: 1, max_length: 100),
160
648
  "email" => T.email,
161
- "age" => T.optional(T.integer(min: 0, max: 150)),
162
- "profile" => T.optional(T.hash({
163
- "bio" => T.string(max_length: 500),
164
- "avatar_url" => T.string(format: :url)
165
- }))
649
+ "age" => T.optional(T.integer(minimum: 0, maximum: 150)),
650
+ "preferences" => T.optional(T.hash({
651
+ "theme" => T.string(enum: %w[light dark auto]),
652
+ "notifications" => T.boolean,
653
+ "languages" => T.array(T.string)
654
+ })),
655
+ "metadata" => T.optional(T.hash({})) # Free-form metadata
656
+ })
657
+
658
+ # Auto-derive schemas from existing data
659
+ INFERRED_SCHEMA = T.from_hash({
660
+ id: 1,
661
+ name: "John Doe",
662
+ active: true,
663
+ tags: ["admin", "power-user"]
166
664
  })
167
665
  ```
168
666
 
169
- ### Fluent Endpoint Definition
667
+ ### ๐Ÿš€ Enhanced HTTP Verb DSL
170
668
 
171
- Create endpoints with a clean, readable DSL:
669
+ Fluent, chainable endpoint definitions:
172
670
 
173
671
  ```ruby
174
- # Using the enhanced HTTP verb DSL with T shortcut
672
+ # All HTTP verbs available with full type safety
175
673
  endpoint(
176
- GET('/users/:id')
177
- .summary('Get user by ID')
178
- .path_param(:id, T.integer(minimum: 1))
179
- .query(:include, T.optional(T.array(T.string)), description: 'Related data to include')
180
- .ok(USER_SCHEMA)
181
- .error_response(404, T.hash({ "error" => T.string }), description: 'User not found')
182
- .error_response(422, T.hash({
674
+ POST('/users')
675
+ .summary('Create a new user')
676
+ .description('Creates a user with validation and returns the created resource')
677
+ .tags('Users', 'CRUD')
678
+ .body(USER_SCHEMA, description: 'User data to create')
679
+ .header('X-Request-ID', T.optional(T.string), description: 'Request tracking ID')
680
+ .ok(USER_SCHEMA, description: 'Successfully created user')
681
+ .error_response(400, T.hash({
183
682
  "error" => T.string,
184
- "details" => T.array(T.hash({
683
+ "validation_errors" => T.array(T.hash({
185
684
  "field" => T.string,
186
- "message" => T.string
685
+ "message" => T.string,
686
+ "code" => T.string
187
687
  }))
188
- }))
688
+ }), description: 'Validation failed')
689
+ .error_response(409, T.hash({ "error" => T.string }), description: 'User already exists')
189
690
  .build
190
691
  ) do |inputs|
191
- user = User.find(inputs[:id])
192
- halt 404, { error: 'User not found' }.to_json unless user
193
-
194
- # Handle optional includes
195
- if inputs[:include]&.include?('profile')
196
- user = user.with_profile
692
+ begin
693
+ user = UserService.create(inputs[:body])
694
+ status 201
695
+ user.to_h
696
+ rescue ValidationError => e
697
+ halt 400, {
698
+ error: 'Validation failed',
699
+ validation_errors: e.details
700
+ }.to_json
701
+ rescue ConflictError => e
702
+ halt 409, { error: e.message }.to_json
197
703
  end
198
-
199
- user.to_h
200
704
  end
201
705
  ```
202
706
 
203
- ### RESTful Resource Builder
707
+ ### ๐Ÿญ RESTful Resource Builder
204
708
 
205
- Build complete CRUD APIs with minimal code:
709
+ Complete CRUD APIs with minimal code:
206
710
 
207
711
  ```ruby
208
- # Enhanced resource builder with custom validations and relationships
209
712
  api_resource '/users', schema: USER_SCHEMA do
210
- crud do
211
- index do
212
- # Automatic pagination and filtering
713
+ # Configure resource-level settings
714
+ configure do
715
+ pagination default_limit: 25, max_limit: 100
716
+ filtering allow: [:name, :email, :active]
717
+ sorting allow: [:name, :created_at, :updated_at]
718
+ end
719
+
720
+ crud except: [:destroy] do # Exclude dangerous operations
721
+ index do |inputs|
213
722
  users = User.all
214
- users = users.where(active: true) if params[:active] == 'true'
215
- users.limit(params[:limit] || 50)
723
+ users = users.where(active: true) if inputs[:filter_active]
724
+ users = users.search(inputs[:search]) if inputs[:search]
725
+
726
+ paginated_response(
727
+ data: users.map(&:to_h),
728
+ page: inputs[:page] || 1,
729
+ per_page: inputs[:per_page] || 25,
730
+ total: users.count
731
+ )
216
732
  end
217
733
 
218
- show { |inputs| User.find(inputs[:id]) }
734
+ show { |inputs| User.find(inputs[:id])&.to_h || halt(404) }
219
735
 
220
736
  create do |inputs|
221
- user = User.create(inputs[:body])
737
+ user = User.create!(inputs[:body])
222
738
  status 201
739
+ location "/users/#{user.id}"
223
740
  user.to_h
224
741
  end
225
742
 
226
- update { |inputs| User.update(inputs[:id], inputs[:body]) }
227
- destroy { |inputs| User.delete(inputs[:id]); status 204 }
743
+ update do |inputs|
744
+ user = User.find(inputs[:id]) || halt(404)
745
+ user.update!(inputs[:body])
746
+ user.to_h
747
+ end
228
748
  end
229
749
 
230
- # Add custom endpoints with full type safety
231
- custom :get, 'active' do
232
- User.where(active: true).map(&:to_h)
750
+ # Custom endpoints with full inheritance of resource configuration
751
+ custom :post, ':id/avatar' do |inputs|
752
+ user = User.find(inputs[:id]) || halt(404)
753
+ avatar = user.update_avatar(inputs[:body][:avatar_data])
754
+ { avatar_url: avatar.url, updated_at: avatar.updated_at }
233
755
  end
234
756
 
235
- custom :post, ':id/avatar' do |inputs|
236
- user = User.find(inputs[:id])
237
- user.update_avatar(inputs[:body][:avatar_data])
238
- { success: true }
757
+ custom :get, 'search/advanced' do |inputs|
758
+ # Advanced search with multiple criteria
759
+ results = UserSearchService.advanced_search(inputs)
760
+ { users: results.map(&:to_h), search_metadata: results.metadata }
239
761
  end
240
762
  end
241
763
  ```
242
764
 
243
- ### Automatic OpenAPI Documentation
765
+ ### ๐Ÿ“– Automatic Documentation
244
766
 
245
- Your API documentation is always up-to-date because it's generated from your actual code:
767
+ Your API documentation is always up-to-date:
246
768
 
247
- - **Interactive Swagger UI** with try-it-out functionality
248
- - **Complete OpenAPI 3.0 specification** with schemas, examples, and security
249
- - **TypeScript client generation** for frontend teams
250
- - **Markdown documentation** for wikis and READMEs
769
+ - **Interactive Swagger UI**: Try endpoints directly from the browser
770
+ - **Complete OpenAPI 3.0**: Full specification with schemas, examples, security
771
+ - **TypeScript clients**: Auto-generated for frontend teams
772
+ - **Markdown docs**: Perfect for wikis and README files
773
+ - **CLI generation**: `rapitapir generate docs --format html`
251
774
 
252
775
  ## ๐Ÿ”ง Framework Integration
253
776
 
254
777
  ### Sinatra (Recommended)
255
778
 
256
- **Option 1: Clean Base Class (Recommended)**
779
+ **Option 1: SinatraRapiTapir Base Class**
257
780
  ```ruby
258
781
  require 'rapitapir'
259
782
 
260
783
  class MyAPI < SinatraRapiTapir
261
784
  rapitapir do
262
- info(title: 'My API', version: '1.0.0')
785
+ info(title: 'My API', version: '2.0.0')
263
786
  development_defaults!
264
787
  end
265
- # Enhanced HTTP verb DSL automatically available
788
+ # Enhanced HTTP verb DSL + T shortcut automatically available
266
789
  end
267
790
  ```
268
791
 
269
- **Option 2: Manual Extension Registration**
792
+ **Option 2: Manual Extension**
270
793
  ```ruby
271
794
  require 'rapitapir/sinatra/extension'
272
795
 
273
796
  class MyAPI < Sinatra::Base
274
797
  register RapiTapir::Sinatra::Extension
275
- # Use the full DSL...
798
+ # Use full DSL manually...
799
+ end
800
+ ```
801
+
802
+ ### Rails Integration
803
+
804
+ ```ruby
805
+ # app/controllers/api/base_controller.rb
806
+ class Api::BaseController < ApplicationController
807
+ include RapiTapir::Server::Rails::ControllerBase
808
+
809
+ rapitapir do
810
+ info(title: 'Rails API', version: '1.0.0')
811
+ bearer_auth :jwt
812
+ end
813
+ end
814
+
815
+ # app/controllers/api/users_controller.rb
816
+ class Api::UsersController < Api::BaseController
817
+ endpoint(
818
+ GET('/users')
819
+ .summary('List users')
820
+ .ok(T.array(USER_SCHEMA))
821
+ .build
822
+ ) { User.all.map(&:to_h) }
276
823
  end
277
824
  ```
278
825
 
@@ -282,204 +829,760 @@ end
282
829
  require 'rapitapir/server/rack_adapter'
283
830
 
284
831
  class MyRackApp
285
- def call(env)
286
- # Manual integration with Rack
832
+ include RapiTapir::Server::RackAdapter
833
+
834
+ def initialize
835
+ register_endpoints
836
+ end
837
+
838
+ private
839
+
840
+ def register_endpoints
841
+ endpoint(GET('/status').ok(T.hash({ "status" => T.string })).build) do
842
+ { status: 'ok' }
843
+ end
844
+ end
845
+ end
846
+ ```
847
+
848
+ ## โ˜๏ธ Serverless Deployment
849
+
850
+ RapiTapir APIs can be deployed as serverless functions across all major cloud providers with zero configuration changes. The same SinatraRapiTapir code runs seamlessly on AWS Lambda, Google Cloud Functions, Azure Functions, and Vercel.
851
+
852
+ ### ๐Ÿš€ AWS Lambda
853
+
854
+ ```ruby
855
+ require 'rapitapir'
856
+
857
+ class ServerlessAPI < SinatraRapiTapir
858
+ rapitapir do
859
+ info(title: 'Serverless API', version: '1.0.0')
860
+ development_defaults!
287
861
  end
862
+
863
+ endpoint(GET('/hello').query(:name, T.string).ok(T.hash({"message" => T.string})).build) do |inputs|
864
+ { message: "Hello from Lambda, #{inputs[:name]}!" }
865
+ end
866
+ end
867
+
868
+ # Lambda handler
869
+ def lambda_handler(event:, context:)
870
+ rack_env = build_rack_env_from_api_gateway(event, context)
871
+ app = ServerlessAPI.new
872
+ status, headers, body = app.call(rack_env)
873
+ build_api_gateway_response(status, headers, body)
874
+ end
875
+ ```
876
+
877
+ **Deploy with AWS SAM**:
878
+ ```bash
879
+ sam build && sam deploy
880
+ ```
881
+
882
+ ### โ˜๏ธ Google Cloud Functions
883
+
884
+ ```ruby
885
+ require 'functions_framework'
886
+
887
+ FunctionsFramework.http('my_api') do |request|
888
+ rack_env = build_rack_env_from_cloud_functions(request)
889
+ app = ServerlessAPI.new
890
+ app.call(rack_env)
288
891
  end
289
892
  ```
290
893
 
291
- ### Rails Support
894
+ **Deploy**:
895
+ ```bash
896
+ gcloud functions deploy my-api --runtime ruby32 --trigger-http
897
+ ```
898
+
899
+ ### ๐ŸŒ Vercel Edge Functions
292
900
 
293
901
  ```ruby
294
- # In your Rails controller
295
- include RapiTapir::Rails::Controller
902
+ def handler(request:, response:)
903
+ rack_env = build_rack_env_from_vercel(request)
904
+ app = ServerlessAPI.new
905
+ status, headers, body = app.call(rack_env)
906
+
907
+ response.status = status
908
+ headers.each { |k, v| response[k] = v }
909
+ response.write(body.join)
910
+ end
296
911
  ```
297
912
 
913
+ **Deploy**:
914
+ ```bash
915
+ vercel --prod
916
+ ```
917
+
918
+ ### Key Benefits
919
+
920
+ - **๐Ÿš€ Zero Cold Start Impact**: Optimized for fast function startup
921
+ - **๐Ÿ’ฐ Cost Effective**: Pay only for actual requests
922
+ - **๐ŸŒ Global Scale**: Deploy to edge locations worldwide
923
+ - **๐Ÿ”’ Built-in Security**: Leverage cloud provider security
924
+ - **๐Ÿ“Š Native Monitoring**: Integrate with cloud monitoring
925
+
926
+ ### Complete Examples
927
+
928
+ See [examples/serverless/](examples/serverless/) for production-ready examples including:
929
+
930
+ - **AWS Lambda + API Gateway**: Full SAM template with DynamoDB
931
+ - **Google Cloud Functions**: With Firestore integration
932
+ - **Azure Functions**: With Cosmos DB and Service Bus
933
+ - **Vercel Edge**: With global edge caching
934
+ - **Multi-cloud deployment**: GitHub Actions workflows
935
+
298
936
  ## ๐Ÿ›ก๏ธ Production Features
299
937
 
300
- ### Authentication & Authorization
938
+ ### ๐Ÿ” Authentication & Authorization
301
939
 
302
940
  ```ruby
303
- # Bearer token authentication with enhanced syntax
304
941
  class SecureAPI < SinatraRapiTapir
305
942
  rapitapir do
306
- info(title: 'Secure API', version: '1.0.0')
943
+ info(title: 'Secure API', version: '2.0.0')
944
+
945
+ # Multiple auth schemes supported
307
946
  bearer_auth :api_key, realm: 'API'
947
+ oauth2_auth0 :auth0, domain: ENV['AUTH0_DOMAIN'], audience: ENV['AUTH0_AUDIENCE']
948
+ basic_auth :admin, realm: 'Admin Panel'
949
+
950
+ production_defaults! # Security headers, rate limiting, HTTPS enforcement
951
+ end
952
+
953
+ # Scope-based protection
954
+ protect_with_oauth2 scopes: ['api:read'] do
955
+ endpoint(GET('/protected/data').ok(T.array(T.hash({}))).build) { ProtectedData.all }
956
+ end
957
+
958
+ # Fine-grained permissions
959
+ endpoint(
960
+ DELETE('/admin/users/:id')
961
+ .path_param(:id, T.integer)
962
+ .bearer_auth(scopes: ['admin', 'users:delete'])
963
+ .ok(T.hash({ "message" => T.string }))
964
+ .build
965
+ ) do |inputs|
966
+ require_scope!('admin') # Additional runtime check
967
+ UserService.delete(inputs[:id])
968
+ { message: 'User deleted successfully' }
969
+ end
970
+ end
971
+ ```
972
+
973
+ ### ๐Ÿ“Š Observability & Monitoring
974
+
975
+ ```ruby
976
+ class MonitoredAPI < SinatraRapiTapir
977
+ rapitapir do
978
+ info(title: 'Production API', version: '2.0.0')
979
+
980
+ enable_observability do |config|
981
+ # Health checks with custom probes
982
+ config.health_checks.enable(path: '/health')
983
+ config.health_checks.add_check('database') { Database.healthy? }
984
+ config.health_checks.add_check('redis') { Redis.current.ping == 'PONG' }
985
+
986
+ # OpenTelemetry integration
987
+ config.tracing.enable_opentelemetry(
988
+ service_name: 'my-api',
989
+ exporters: [:honeycomb, :jaeger],
990
+ sample_rate: 0.1
991
+ )
992
+
993
+ # Prometheus metrics
994
+ config.metrics.enable_prometheus(
995
+ namespace: 'my_api',
996
+ path: '/metrics'
997
+ )
998
+
999
+ # Structured logging
1000
+ config.logging.enable_structured(format: :json)
1001
+ end
1002
+ end
1003
+
1004
+ # Endpoints with observability
1005
+ endpoint(
1006
+ GET('/monitored-endpoint')
1007
+ .with_metrics('endpoint_requests', labels: { operation: 'get' })
1008
+ .with_tracing('fetch_data')
1009
+ .ok(T.hash({}))
1010
+ .build
1011
+ ) do
1012
+ # Custom spans and metrics automatically collected
1013
+ { data: 'response' }
1014
+ end
1015
+ end
1016
+ ```
1017
+
1018
+ ### ๐Ÿ”’ Security Middleware
1019
+
1020
+ Built-in security features for production deployments:
1021
+
1022
+ ```ruby
1023
+ # Automatic security middleware
1024
+ use RapiTapir::Server::Middleware::SecurityHeaders
1025
+ use RapiTapir::Server::Middleware::RateLimit, requests_per_minute: 100
1026
+ use RapiTapir::Server::Middleware::CORS, origins: ['https://myapp.com']
1027
+ use RapiTapir::Server::Middleware::RequestValidation
1028
+ ```
1029
+
1030
+ ## ๐Ÿค– AI Integration Features
1031
+
1032
+ ### LLM Instruction Generation
1033
+
1034
+ Generate context-aware instructions for any endpoint:
1035
+
1036
+ ```ruby
1037
+ # Generate instructions for different AI purposes
1038
+ generator = RapiTapir::AI::LLMInstruction::Generator.new
1039
+
1040
+ # Validation instructions
1041
+ validation_prompt = generator.generate_instructions(
1042
+ endpoint: my_endpoint,
1043
+ purpose: :validation
1044
+ )
1045
+
1046
+ # Documentation instructions
1047
+ docs_prompt = generator.generate_instructions(
1048
+ endpoint: my_endpoint,
1049
+ purpose: :documentation
1050
+ )
1051
+
1052
+ # Test generation instructions
1053
+ test_prompt = generator.generate_instructions(
1054
+ endpoint: my_endpoint,
1055
+ purpose: :testing
1056
+ )
1057
+ ```
1058
+
1059
+ ### RAG (Retrieval-Augmented Generation)
1060
+
1061
+ Enable semantic search and context-aware responses:
1062
+
1063
+ ```ruby
1064
+ endpoint(
1065
+ GET('/books/semantic-search')
1066
+ .query(:query, T.string)
1067
+ .enable_rag(
1068
+ retrieval_backend: :memory, # or :elasticsearch, :postgresql
1069
+ llm_provider: :openai,
1070
+ context_window: 4000
1071
+ )
1072
+ .ok(T.hash({
1073
+ "results" => T.array(BOOK_SCHEMA),
1074
+ "context" => T.string,
1075
+ "confidence" => T.float
1076
+ }))
1077
+ .build
1078
+ ) do |inputs|
1079
+ # RAG context automatically injected
1080
+ rag_enhanced_search(inputs[:query], context: rag_context)
1081
+ end
1082
+ ```
1083
+
1084
+ ### Model Context Protocol (MCP)
1085
+
1086
+ Export your API for AI agent consumption:
1087
+
1088
+ ```ruby
1089
+ # Export MCP-compatible JSON
1090
+ exporter = RapiTapir::AI::MCP::Exporter.new(rapitapir_endpoints)
1091
+ mcp_json = exporter.export_json(pretty: true)
1092
+
1093
+ # CLI export
1094
+ # rapitapir mcp export --output api-context.json
1095
+ ```
1096
+
1097
+ ## ๐ŸŽจ Complete Examples
1098
+
1099
+ ### ๐Ÿ“š Library Management System
1100
+
1101
+ A comprehensive example showcasing all features:
1102
+
1103
+ ```ruby
1104
+ require 'rapitapir'
1105
+
1106
+ class LibraryAPI < SinatraRapiTapir
1107
+ rapitapir do
1108
+ info(
1109
+ title: 'Library Management System',
1110
+ description: 'Complete library API with AI, auth, and observability',
1111
+ version: '2.0.0',
1112
+ contact: { name: 'API Team', email: 'api@library.com' }
1113
+ )
1114
+
1115
+ # Auth configuration
1116
+ oauth2_auth0 :auth0,
1117
+ domain: ENV['AUTH0_DOMAIN'],
1118
+ audience: ENV['AUTH0_AUDIENCE']
1119
+
1120
+ # Observability
1121
+ enable_observability do |config|
1122
+ config.health_checks.enable
1123
+ config.tracing.enable_opentelemetry(service_name: 'library-api')
1124
+ config.metrics.enable_prometheus
1125
+ end
1126
+
308
1127
  production_defaults!
309
1128
  end
310
1129
 
311
- # Protected endpoint with scope-based authorization
1130
+ # Schemas
1131
+ BOOK_SCHEMA = T.hash({
1132
+ "id" => T.integer,
1133
+ "isbn" => T.string(pattern: /^\d{13}$/),
1134
+ "title" => T.string(min_length: 1, max_length: 500),
1135
+ "authors" => T.array(T.string),
1136
+ "published_date" => T.date,
1137
+ "genres" => T.array(T.string),
1138
+ "available_copies" => T.integer(minimum: 0),
1139
+ "total_copies" => T.integer(minimum: 1),
1140
+ "metadata" => T.optional(T.hash({}))
1141
+ })
1142
+
1143
+ MEMBER_SCHEMA = T.hash({
1144
+ "id" => T.integer,
1145
+ "email" => T.email,
1146
+ "name" => T.string(min_length: 1),
1147
+ "member_since" => T.date,
1148
+ "active" => T.boolean,
1149
+ "borrowed_books" => T.array(T.integer)
1150
+ })
1151
+
1152
+ # Public endpoints
312
1153
  endpoint(
313
- GET('/admin/users')
314
- .summary('List all users (admin only)')
315
- .bearer_auth(scopes: ['admin'])
316
- .query(:page, T.optional(T.integer(minimum: 1)), description: 'Page number')
317
- .query(:per_page, T.optional(T.integer(minimum: 1, maximum: 100)), description: 'Items per page')
1154
+ GET('/books/search')
1155
+ .query(:q, T.string(min_length: 1), description: 'Search query')
1156
+ .query(:ai_enhanced, T.optional(T.boolean), description: 'Use AI semantic search')
1157
+ .summary('Search books with optional AI enhancement')
1158
+ .tags('Books', 'Search')
318
1159
  .ok(T.hash({
319
- "users" => T.array(USER_SCHEMA),
320
- "pagination" => T.hash({
321
- "page" => T.integer,
322
- "per_page" => T.integer,
323
- "total" => T.integer,
324
- "pages" => T.integer
325
- })
1160
+ "books" => T.array(BOOK_SCHEMA),
1161
+ "total" => T.integer,
1162
+ "ai_enhanced" => T.boolean
326
1163
  }))
327
- .error_response(401, T.hash({ "error" => T.string }), description: 'Unauthorized')
328
- .error_response(403, T.hash({ "error" => T.string }), description: 'Insufficient permissions')
1164
+ .enable_rag
1165
+ .enable_mcp
329
1166
  .build
330
1167
  ) do |inputs|
331
- require_scope!('admin')
332
-
333
- page = inputs[:page] || 1
334
- per_page = inputs[:per_page] || 20
335
-
336
- users = User.paginate(page: page, per_page: per_page)
1168
+ if inputs[:ai_enhanced]
1169
+ results = AIBookSearch.semantic_search(inputs[:q], context: rag_context)
1170
+ else
1171
+ results = Book.search(inputs[:q])
1172
+ end
337
1173
 
338
1174
  {
339
- users: users.map(&:to_h),
340
- pagination: {
341
- page: page,
342
- per_page: per_page,
343
- total: users.total_count,
344
- pages: users.total_pages
345
- }
1175
+ books: results.map(&:to_h),
1176
+ total: results.count,
1177
+ ai_enhanced: !!inputs[:ai_enhanced]
346
1178
  }
347
1179
  end
1180
+
1181
+ # Protected member endpoints
1182
+ protect_with_oauth2 scopes: ['library:read'] do
1183
+ api_resource '/books', schema: BOOK_SCHEMA do
1184
+ crud only: [:index, :show] do
1185
+ index { Book.available.map(&:to_h) }
1186
+ show { |inputs| Book.find(inputs[:id])&.to_h || halt(404) }
1187
+ end
1188
+
1189
+ custom :post, ':id/reserve' do |inputs|
1190
+ book = Book.find(inputs[:id]) || halt(404)
1191
+ member = current_member
1192
+
1193
+ reservation = ReservationService.create(book: book, member: member)
1194
+ { reservation_id: reservation.id, expires_at: reservation.expires_at }
1195
+ end
1196
+ end
1197
+
1198
+ endpoint(
1199
+ GET('/members/me/profile')
1200
+ .summary('Get current member profile')
1201
+ .bearer_auth(scopes: ['profile:read'])
1202
+ .ok(MEMBER_SCHEMA)
1203
+ .build
1204
+ ) { current_member.to_h }
1205
+ end
1206
+
1207
+ # Admin endpoints
1208
+ protect_with_oauth2 scopes: ['library:admin'] do
1209
+ api_resource '/admin/books', schema: BOOK_SCHEMA do
1210
+ crud do
1211
+ index { Book.all.map(&:to_h) }
1212
+ show { |inputs| Book.find(inputs[:id])&.to_h || halt(404) }
1213
+ create { |inputs| Book.create!(inputs[:body]).to_h }
1214
+ update { |inputs| Book.update!(inputs[:id], inputs[:body]).to_h }
1215
+ destroy { |inputs| Book.destroy(inputs[:id]); status 204 }
1216
+ end
1217
+ end
1218
+
1219
+ # AI-powered book recommendations
1220
+ endpoint(
1221
+ POST('/admin/ai/recommend-acquisitions')
1222
+ .body(T.hash({
1223
+ "budget" => T.float(minimum: 0),
1224
+ "categories" => T.optional(T.array(T.string)),
1225
+ "member_preferences" => T.optional(T.boolean)
1226
+ }))
1227
+ .summary('Get AI-powered book acquisition recommendations')
1228
+ .tags('Admin', 'AI', 'Recommendations')
1229
+ .ok(T.hash({
1230
+ "recommendations" => T.array(T.hash({
1231
+ "title" => T.string,
1232
+ "author" => T.string,
1233
+ "estimated_cost" => T.float,
1234
+ "demand_score" => T.float,
1235
+ "reasoning" => T.string
1236
+ })),
1237
+ "total_estimated_cost" => T.float,
1238
+ "confidence" => T.float
1239
+ }))
1240
+ .enable_llm_instructions(purpose: :completion)
1241
+ .build
1242
+ ) do |inputs|
1243
+ recommendations = AIAcquisitionService.recommend(
1244
+ budget: inputs[:budget],
1245
+ categories: inputs[:categories],
1246
+ consider_member_preferences: inputs[:member_preferences],
1247
+ context: library_context
1248
+ )
1249
+
1250
+ {
1251
+ recommendations: recommendations[:items],
1252
+ total_estimated_cost: recommendations[:total_cost],
1253
+ confidence: recommendations[:confidence_score]
1254
+ }
1255
+ end
1256
+ end
1257
+
1258
+ run! if __FILE__ == $0
348
1259
  end
349
1260
  ```
350
1261
 
351
- ### Observability
1262
+ ### ๐Ÿฅ Healthcare API Example
352
1263
 
353
1264
  ```ruby
354
- class MonitoredAPI < SinatraRapiTapir
1265
+ class HealthcareAPI < SinatraRapiTapir
355
1266
  rapitapir do
356
- info(title: 'Monitored API', version: '1.0.0')
357
- enable_health_checks path: '/health'
358
- enable_metrics
1267
+ info(
1268
+ title: 'Healthcare Management API',
1269
+ description: 'HIPAA-compliant healthcare API with AI diagnostics',
1270
+ version: '2.0.0'
1271
+ )
1272
+
1273
+ # Strict security for healthcare
1274
+ bearer_auth :jwt, realm: 'Healthcare'
1275
+
1276
+ enable_observability do |config|
1277
+ config.health_checks.enable
1278
+ config.tracing.enable_opentelemetry(
1279
+ service_name: 'healthcare-api',
1280
+ compliance_mode: :hipaa
1281
+ )
1282
+ config.logging.enable_structured(
1283
+ format: :json,
1284
+ exclude_fields: [:ssn, :medical_record_number] # PII protection
1285
+ )
1286
+ end
1287
+
359
1288
  production_defaults!
360
1289
  end
361
1290
 
362
- # Endpoint with metrics and tracing
1291
+ PATIENT_SCHEMA = T.hash({
1292
+ "id" => T.string, # UUID for privacy
1293
+ "name" => T.hash({
1294
+ "first" => T.string,
1295
+ "last" => T.string
1296
+ }),
1297
+ "date_of_birth" => T.date,
1298
+ "medical_record_number" => T.string,
1299
+ "insurance" => T.optional(T.hash({}))
1300
+ })
1301
+
1302
+ # AI-powered diagnostic assistance
363
1303
  endpoint(
364
- GET('/api/data')
365
- .summary('Get data with monitoring')
366
- .with_metrics('api_data_requests')
367
- .with_tracing('fetch_api_data')
368
- .query(:filter, T.optional(T.string), description: 'Data filter')
1304
+ POST('/diagnostics/analyze')
1305
+ .body(T.hash({
1306
+ "patient_id" => T.string,
1307
+ "symptoms" => T.array(T.string),
1308
+ "vital_signs" => T.hash({
1309
+ "temperature" => T.optional(T.float),
1310
+ "blood_pressure" => T.optional(T.string),
1311
+ "heart_rate" => T.optional(T.integer)
1312
+ }),
1313
+ "medical_history" => T.optional(T.array(T.string))
1314
+ }))
1315
+ .summary('AI-assisted diagnostic analysis')
1316
+ .bearer_auth(scopes: ['diagnostics:read', 'ai:analyze'])
1317
+ .tags('Diagnostics', 'AI')
369
1318
  .ok(T.hash({
370
- "data" => T.array(T.hash({
371
- "id" => T.integer,
372
- "value" => T.string,
373
- "timestamp" => T.datetime
374
- })),
375
- "metadata" => T.hash({
376
- "total" => T.integer,
377
- "filtered" => T.boolean
378
- })
1319
+ "analysis" => T.hash({
1320
+ "suggested_conditions" => T.array(T.hash({
1321
+ "condition" => T.string,
1322
+ "confidence" => T.float,
1323
+ "reasoning" => T.string
1324
+ })),
1325
+ "recommended_tests" => T.array(T.string),
1326
+ "urgency_level" => T.string(enum: %w[low medium high critical])
1327
+ }),
1328
+ "disclaimer" => T.string,
1329
+ "generated_at" => T.datetime
379
1330
  }))
1331
+ .enable_llm_instructions(purpose: :analysis)
380
1332
  .build
381
1333
  ) do |inputs|
382
- # Your endpoint code with automatic metrics collection
383
- data = DataService.fetch(filter: inputs[:filter])
1334
+ # Verify provider permissions
1335
+ require_scope!('diagnostics:read')
1336
+
1337
+ # AI diagnostic analysis with medical context
1338
+ analysis = MedicalAI.analyze_symptoms(
1339
+ patient_id: inputs[:patient_id],
1340
+ symptoms: inputs[:symptoms],
1341
+ vital_signs: inputs[:vital_signs],
1342
+ medical_history: inputs[:medical_history],
1343
+ provider_context: current_provider_context
1344
+ )
384
1345
 
385
1346
  {
386
- data: data.map(&:to_h),
387
- metadata: {
388
- total: data.count,
389
- filtered: inputs[:filter].present?
390
- }
1347
+ analysis: analysis,
1348
+ disclaimer: "This analysis is for informational purposes only and should not replace professional medical judgment.",
1349
+ generated_at: Time.now
391
1350
  }
392
1351
  end
1352
+
1353
+ run! if __FILE__ == $0
393
1354
  end
394
1355
  ```
395
1356
 
396
- ### Security Middleware
1357
+ ## ๐Ÿ“š Documentation
1358
+
1359
+ ### Core Guides
1360
+
1361
+ - **[Getting Started Guide](examples/working_simple_example.rb)** - Your first RapiTapir API in 5 minutes
1362
+ - **[SinatraRapiTapir Base Class](docs/sinatra_rapitapir.md)** - Zero-boilerplate API creation
1363
+ - **[Enhanced HTTP DSL](docs/endpoint-definition.md)** - Complete endpoint definition guide
1364
+ - **[Type System & T Shortcut](docs/type_shortcuts.md)** - All available types and validations
1365
+ - **[Resource Builder](docs/RAILS_INTEGRATION_IMPLEMENTATION.md)** - RESTful CRUD with minimal code
1366
+
1367
+ ### Advanced Features
1368
+
1369
+ - **[AI Integration](docs/auto-derivation.md)** - LLM instructions, RAG pipelines, MCP export
1370
+ - **[Authentication & Security](examples/authentication_example.rb)** - OAuth2, JWT, scopes, and Auth0
1371
+ - **[Observability](docs/observability.md)** - OpenTelemetry, health checks, metrics
1372
+ - **[CLI Toolkit](docs/blueprint.md)** - Complete command-line development workflow
1373
+
1374
+ ### Framework Integration
1375
+
1376
+ - **[Sinatra Extension](docs/SINATRA_EXTENSION.md)** - Detailed Sinatra integration guide
1377
+ - **[Rails Integration](docs/RAILS_INTEGRATION_IMPLEMENTATION.md)** - Controller-based Rails APIs
1378
+ - **[Rack Applications](docs/implementation-status.md)** - Direct Rack integration
1379
+
1380
+ ### Examples & Templates
1381
+
1382
+ Explore our comprehensive examples directory:
1383
+
1384
+ - **[Hello World](examples/hello_world.rb)** - 30-second minimal example
1385
+ - **[Enterprise API](examples/enterprise_rapitapir_api.rb)** - Production-ready with all features
1386
+ - **[Serverless Deployment](examples/serverless/)** - AWS Lambda, Google Cloud Functions, Azure Functions, Vercel
1387
+ - **[OAuth2 + Auth0](examples/oauth2/)** - Complete authentication examples
1388
+ - **[AI-Powered APIs](examples/auto_derivation_ruby_friendly.rb)** - LLM and RAG integration
1389
+ - **[Observability Setup](examples/observability/)** - Monitoring and health checks
1390
+ - **[CLI Examples](examples/cli/)** - Command-line toolkit usage
1391
+
1392
+ ## Architecture Decision Records (ADRs)
1393
+
1394
+ Key architectural decisions are tracked in `docs/adr/`:
1395
+
1396
+ - ADR index and guidelines: [docs/adr/README.md](docs/adr/README.md)
1397
+ - Template: [docs/adr/template.md](docs/adr/template.md)
1398
+
1399
+ Initial ADRs:
1400
+
1401
+ - [ADR-0001: Base class strategy (SinatraRapiTapir) vs manual extension](docs/adr/0001-base-class-strategy.md)
1402
+ - [ADR-0002: Type shortcut (T) and type system boundaries](docs/adr/0002-type-shortcut-and-type-system.md)
1403
+ - [ADR-0003: OpenAPI source-of-truth and doc generation flow](docs/adr/0003-openapi-source-of-truth.md)
1404
+ - [ADR-0004: Client generation target (TypeScript first) and interface conventions](docs/adr/0004-client-generation-typescript-first.md)
1405
+ - [ADR-0005: Authentication architecture (schemes + helpers + middleware)](docs/adr/0005-auth-architecture.md)
1406
+ - [ADR-0006: Observability defaults (health, logging, metrics/tracing hooks)](docs/adr/0006-observability-defaults.md)
1407
+ - [ADR-0007: AI features scope (RAG/LLM/MCP) and maintainability boundaries](docs/adr/0007-ai-scope-and-boundaries.md)
1408
+
1409
+
1410
+ ## ๐Ÿ› ๏ธ CLI Development Toolkit
1411
+
1412
+ RapiTapir includes a powerful CLI for streamlined development:
1413
+
1414
+ ### Code Generation
1415
+ ```bash
1416
+ # Generate OpenAPI specifications
1417
+ rapitapir generate openapi --output api-spec.json --format json
1418
+ rapitapir generate openapi --output api-spec.yaml --format yaml
1419
+
1420
+ # Generate TypeScript clients
1421
+ rapitapir generate client typescript --output client/api.ts
1422
+ rapitapir generate client python --output client/api.py
1423
+
1424
+ # Generate documentation
1425
+ rapitapir generate docs html --output docs/api.html
1426
+ rapitapir generate docs markdown --output API.md
1427
+ ```
1428
+
1429
+ ### AI-Powered Features
1430
+ ```bash
1431
+ # Generate LLM instructions for specific endpoints
1432
+ rapitapir llm generate --endpoint-id "get_users" --purpose validation
1433
+ rapitapir llm generate --endpoint-id "create_book" --purpose testing
397
1434
 
398
- ```ruby
399
- # Built-in security features
400
- use RapiTapir::Server::Middleware::CORS
401
- use RapiTapir::Server::Middleware::RateLimit, requests_per_minute: 100
402
- use RapiTapir::Server::Middleware::SecurityHeaders
1435
+ # Export LLM instructions for all endpoints
1436
+ rapitapir llm export --format instructions --output ai-prompts/
1437
+
1438
+ # Test LLM instruction generation
1439
+ rapitapir llm test --endpoint-file my_api.rb
1440
+
1441
+ # Export Model Context Protocol for AI agents
1442
+ rapitapir mcp export --output mcp-context.json --format compact
403
1443
  ```
404
1444
 
405
- ## ๐ŸŽจ Examples
1445
+ ### Development & Validation
1446
+ ```bash
1447
+ # Validate endpoint definitions
1448
+ rapitapir validate endpoints --file my_api.rb
1449
+ rapitapir validate openapi --file api-spec.json
406
1450
 
407
- Explore our comprehensive examples:
1451
+ # Serve documentation and specs
1452
+ rapitapir serve --port 3000 --docs-path /documentation
1453
+ rapitapir docs --serve --port 8080 --watch
408
1454
 
409
- - **[Hello World](examples/hello_world.rb)** - Minimal API with SinatraRapiTapir base class
410
- - **[Getting Started](examples/getting_started_extension.rb)** - Complete bookstore API with CRUD operations
411
- - **[Enterprise API](examples/enterprise_rapitapir_api.rb)** - Production-ready example with auth
412
- - **[Authentication](examples/authentication_example.rb)** - Bearer token and scope-based auth
413
- - **[Observability](examples/observability/)** - Health checks, metrics, and tracing
1455
+ # Project scaffolding (coming soon)
1456
+ rapitapir new my-api --template sinatra-ai
1457
+ rapitapir generate scaffold books --with-auth --with-observability
1458
+ ```
414
1459
 
415
- ## ๐Ÿ“š Documentation
1460
+ ### Installation & Setup
416
1461
 
417
- - **[API Reference](docs/endpoint-definition.md)** - Complete endpoint definition guide
418
- - **[SinatraRapiTapir Base Class](docs/sinatra_rapitapir.md)** - Clean inheritance syntax guide
419
- - **[Sinatra Extension](docs/SINATRA_EXTENSION.md)** - Detailed Sinatra integration
420
- - **[Type System](docs/types.md)** - All available types and validations (use `T.` shortcut!)
421
- - **[Authentication](docs/authentication.md)** - Security and auth patterns
422
- - **[Observability](docs/observability.md)** - Monitoring and health checks
423
- - **[GitHub Pages Setup](docs/github_pages_setup.md)** - Documentation deployment guide
1462
+ ```bash
1463
+ # Install the gem
1464
+ gem install rapitapir
424
1465
 
425
- ## ๐Ÿงช Testing
1466
+ # Or add to Gemfile
1467
+ echo 'gem "rapitapir"' >> Gemfile
1468
+ bundle install
1469
+
1470
+ # Verify installation
1471
+ rapitapir --version
1472
+ rapitapir --help
1473
+ ```
426
1474
 
427
- RapiTapir includes comprehensive testing utilities:
1475
+ ## ๐Ÿงช Testing & Quality
428
1476
 
1477
+ RapiTapir includes comprehensive testing utilities and maintains high code quality:
1478
+
1479
+ ### Test Your APIs
429
1480
  ```ruby
430
- # Validate your endpoint definitions
1481
+ # Validate endpoint definitions
431
1482
  RapiTapir::CLI::Validator.new(endpoints).validate
432
1483
 
433
- # Generate test fixtures
434
- RapiTapir::Testing.generate_fixtures(USER_SCHEMA)
1484
+ # Generate test fixtures from schemas
1485
+ test_user = RapiTapir::Testing.generate_fixture(USER_SCHEMA)
1486
+ test_data = RapiTapir::Testing.generate_fixtures(BOOK_SCHEMA, count: 10)
1487
+
1488
+ # Test endpoint types and validation
1489
+ endpoint.validate!({ name: "test", age: 25 }) # Returns validated data
435
1490
  ```
436
1491
 
437
- Run the test suite:
1492
+ ### Quality Metrics
1493
+ - **643 tests passing** with comprehensive coverage
1494
+ - **67.67% line coverage** across the entire codebase
1495
+ - **RuboCop compliance** with zero style violations
1496
+ - **Zero security vulnerabilities** in dependencies
1497
+ - **Continuous integration** with GitHub Actions
438
1498
 
1499
+ ### Run Tests Locally
439
1500
  ```bash
1501
+ # Clone the repository
1502
+ git clone https://github.com/riccardomerolla/rapitapir.git
1503
+ cd rapitapir
1504
+
1505
+ # Install dependencies
1506
+ bundle install
1507
+
1508
+ # Run the test suite
440
1509
  bundle exec rspec
1510
+
1511
+ # Check code style
1512
+ rubocop
1513
+
1514
+ # View coverage report
1515
+ open coverage/index.html
441
1516
  ```
442
1517
 
443
1518
  ## ๐Ÿค Contributing
444
1519
 
445
- We love contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
446
-
447
- ### Development Setup
1520
+ We love contributions! RapiTapir thrives on community input and collaboration.
448
1521
 
1522
+ ### Quick Start Contributing
449
1523
  ```bash
450
1524
  git clone https://github.com/riccardomerolla/rapitapir.git
451
- cd ruby-tapir
1525
+ cd rapitapir
452
1526
  bundle install
453
- bundle exec rspec
1527
+ bundle exec rspec # Ensure all tests pass
454
1528
  ```
455
1529
 
456
- ### Roadmap
1530
+ ### Ways to Contribute
1531
+ - **๐Ÿ› Bug Reports**: [Open an issue](https://github.com/riccardomerolla/rapitapir/issues/new)
1532
+ - **๐Ÿ’ก Feature Requests**: [Start a discussion](https://github.com/riccardomerolla/rapitapir/discussions)
1533
+ - **๐Ÿ“– Documentation**: Improve guides, examples, and API docs
1534
+ - **๐Ÿงช Tests**: Add test coverage for edge cases
1535
+ - **๐ŸŽจ Examples**: Create real-world API examples
1536
+ - **๐Ÿ”Œ Integrations**: Build plugins for other frameworks
1537
+
1538
+ ### Development Roadmap
457
1539
 
458
- - **Phase 4**: Advanced client generation (Python, Go, etc.)
459
- - **Phase 5**: GraphQL integration
460
- - **Phase 6**: gRPC support
461
- - **Community**: Plugin ecosystem
1540
+ **Current Focus (v2.1)**:
1541
+ - Enhanced AI features and LLM provider support
1542
+ - Advanced authentication patterns
1543
+ - Performance optimizations and caching
1544
+ - Extended CLI functionality
462
1545
 
463
- ## ๏ฟฝ License
1546
+ **Upcoming (v3.0)**:
1547
+ - GraphQL integration alongside REST
1548
+ - gRPC support for high-performance APIs
1549
+ - Advanced plugin ecosystem
1550
+ - Multi-language client generation
464
1551
 
465
- RapiTapir is released under the [MIT License](LICENSE).
1552
+ See our [Contributing Guide](CONTRIBUTING.md) for detailed guidelines.
466
1553
 
467
- ## ๐Ÿ™‹โ€โ™‚๏ธ Support
1554
+ ## ๐Ÿ™‹โ€โ™‚๏ธ Support & Community
468
1555
 
1556
+ ### Get Help
469
1557
  - **๐Ÿ› Bug Reports**: [GitHub Issues](https://github.com/riccardomerolla/rapitapir/issues)
470
- - **๐Ÿ’ก Feature Requests**: [GitHub Discussions](https://github.com/riccardomerolla/rapitapir/discussions)
471
- - **๐Ÿ“ง Email**: riccardo.merolla@gmail.com
1558
+ - **๏ฟฝ Questions & Discussions**: [GitHub Discussions](https://github.com/riccardomerolla/rapitapir/discussions)
1559
+ - **๐Ÿ“ง Direct Contact**: riccardo.merolla@gmail.com
1560
+ - **๐Ÿ“– Documentation**: Comprehensive guides in the [docs/](docs/) directory
1561
+
1562
+ ### Community
1563
+ - **โญ Star the Project**: Show your support on [GitHub](https://github.com/riccardomerolla/rapitapir)
1564
+ - **๐Ÿ”— Share**: Help others discover RapiTapir
1565
+ - **๐Ÿค Contribute**: Join the growing community of contributors
472
1566
 
473
1567
  ---
474
1568
 
475
- **Built with โค๏ธ for the Ruby and Sinatra community**
1569
+ ## ๐Ÿ“œ License
476
1570
 
1571
+ RapiTapir is released under the [MIT License](LICENSE). Use it freely in personal and commercial projects.
477
1572
 
478
1573
  ## ๐Ÿ™ Acknowledgments
479
1574
 
480
- Inspired by:
481
- - [Scala Tapir](https://github.com/softwaremill/tapir) - Type-safe endpoints
1575
+ RapiTapir is inspired by excellent projects in the API development space:
1576
+
1577
+ - **[Scala Tapir](https://github.com/softwaremill/tapir)** - Type-safe endpoint definitions that inspired our DSL
1578
+ - **[FastAPI](https://fastapi.tiangolo.com/)** - Automatic documentation and validation patterns
1579
+ - **[Ruby on Rails](https://rubyonrails.org/)** - Convention over configuration philosophy
1580
+ - **[Sinatra](http://sinatrarb.com/)** - Minimalist web framework elegance
1581
+
1582
+ Special thanks to the Ruby and Sinatra communities for their ongoing support and feedback.
482
1583
 
483
1584
  ---
484
1585
 
485
- **RapiTapir** - APIs so fast and clean, they practically run wild! ๐Ÿฆ™โšก
1586
+ **RapiTapir ๐Ÿฆ™** - *APIs so fast, clean, and intelligent, they practically run wild!* โšก๏ฟฝ
1587
+
1588
+ **Built with โค๏ธ for the Ruby community**