rapitapir 2.0.0 → 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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop_todo.yml +5 -0
  3. data/CHANGELOG.md +29 -1
  4. data/README.md +23 -4
  5. data/RUBY_WEEKLY_LAUNCH_POST.md +43 -62
  6. data/docs/adr/0001-base-class-strategy.md +33 -0
  7. data/docs/adr/0002-type-shortcut-and-type-system.md +30 -0
  8. data/docs/adr/0003-openapi-source-of-truth.md +32 -0
  9. data/docs/adr/0004-client-generation-typescript-first.md +34 -0
  10. data/docs/adr/0005-auth-architecture.md +32 -0
  11. data/docs/adr/0006-observability-defaults.md +30 -0
  12. data/docs/adr/0007-ai-scope-and-boundaries.md +30 -0
  13. data/docs/adr/README.md +46 -0
  14. data/docs/adr/template.md +24 -0
  15. data/docs/blueprint.md +92 -4
  16. data/docs/implementation-status.md +1 -1
  17. data/examples/auto_derivation_ruby_friendly.rb +44 -113
  18. data/examples/cli/user_api_endpoints.rb +63 -36
  19. data/examples/demo_api.rb +57 -18
  20. data/examples/enterprise_extension_demo.rb +13 -13
  21. data/examples/enterprise_rapitapir_api.rb +81 -93
  22. data/examples/nocodb/nocodb_scaffold/Gemfile +22 -0
  23. data/examples/nocodb/nocodb_scaffold/README.md +10 -0
  24. data/examples/nocodb/nocodb_scaffold/Rakefile +7 -0
  25. data/examples/nocodb/nocodb_scaffold/app/api/app.rb +1139 -0
  26. data/examples/nocodb/nocodb_scaffold/app/models/email_template.rb +6 -0
  27. data/examples/nocodb/nocodb_scaffold/app/models/faq.rb +6 -0
  28. data/examples/nocodb/nocodb_scaffold/app/models/feature.rb +6 -0
  29. data/examples/nocodb/nocodb_scaffold/app/models/idea.rb +6 -0
  30. data/examples/nocodb/nocodb_scaffold/app/models/itinerary_day.rb +6 -0
  31. data/examples/nocodb/nocodb_scaffold/app/models/route.rb +6 -0
  32. data/examples/nocodb/nocodb_scaffold/app/models/subscriber.rb +6 -0
  33. data/examples/nocodb/nocodb_scaffold/app/models/tour.rb +6 -0
  34. data/examples/nocodb/nocodb_scaffold/app/models/webhook.rb +6 -0
  35. data/examples/nocodb/nocodb_scaffold/app/models_loader.rb +3 -0
  36. data/examples/nocodb/nocodb_scaffold/config/database.yml +11 -0
  37. data/examples/nocodb/nocodb_scaffold/config.ru +9 -0
  38. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152012_create_features.rb +10 -0
  39. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152013_create_tours.rb +10 -0
  40. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152014_create_routes.rb +10 -0
  41. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152015_create_itinerary_days.rb +10 -0
  42. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152016_create_subscribers.rb +10 -0
  43. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152017_create_email_templates.rb +10 -0
  44. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152018_create_faqs.rb +10 -0
  45. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152019_create_webhooks.rb +10 -0
  46. data/examples/nocodb/nocodb_scaffold/db/migrate/20250808152020_create_ideas.rb +10 -0
  47. data/examples/nocodb/swagger.json +4378 -0
  48. data/examples/production_ready_example.rb +78 -58
  49. data/examples/simple_demo_api.rb +40 -7
  50. data/examples/user_api.rb +130 -132
  51. data/lib/rapitapir/auth/oauth2.rb +1 -1
  52. data/lib/rapitapir/cli/command.rb +30 -4
  53. data/lib/rapitapir/cli/scaffold_generator.rb +639 -0
  54. data/lib/rapitapir/cli/validator.rb +1 -1
  55. data/lib/rapitapir/core/enhanced_endpoint.rb +1 -1
  56. data/lib/rapitapir/dsl/enhanced_structures.rb +1 -1
  57. data/lib/rapitapir/openapi/schema_generator.rb +46 -2
  58. data/lib/rapitapir/server/enhanced_rack_adapter.rb +11 -8
  59. data/lib/rapitapir/server/middleware.rb +2 -2
  60. data/lib/rapitapir/types/auto_derivation.rb +2 -4
  61. data/lib/rapitapir/version.rb +1 -1
  62. data/rapitapir.gemspec +3 -2
  63. metadata +70 -8
data/docs/blueprint.md CHANGED
@@ -1,6 +1,94 @@
1
- # Ruby Tapir - Type-Safe HTTP API Library
2
-
3
- A Ruby library for describing, serving, consuming, and documenting HTTP APIs with type safety and developer experience in mind.
1
+ # RapiTapir (formerly "Ruby Tapir") – Type-Safe HTTP API Library
2
+
3
+ A Ruby library for describing, serving, consuming, and documenting HTTP APIs with type safety and great developer experience.
4
+
5
+ ## Status update — August 2025
6
+
7
+ This document started as an early blueprint. The project has since shipped a substantial v2.0 with many areas exceeding the original scope. Below is a concise snapshot of where we are and what we should tackle next.
8
+
9
+ ### What’s implemented and usable today
10
+
11
+ - Core DSL and Types
12
+ - Fluent HTTP verb DSL (GET/POST/PUT/DELETE/HEAD/OPTIONS/PATCH)
13
+ - Global T shortcut (e.g., T.string) and rich type system with validation/coercion
14
+ - Resource builder (CRUD), error responses, metadata (summary, description, tags)
15
+ - Servers and runtime
16
+ - Rack adapter and Sinatra base class (SinatraRapiTapir) with zero-boilerplate startup
17
+ - Middleware: CORS, Security headers, Rate limiting, Request logging, Exception handler
18
+ - Health checks and observability hooks (metrics, logging, tracing scaffolding)
19
+ - Tooling and docs
20
+ - OpenAPI 3.0.3 generator (JSON/YAML) + interactive HTML docs + Markdown docs
21
+ - TypeScript client generator with types and request/response modeling
22
+ - CLI: generate openapi/docs/client, validate, serve
23
+ - Authentication
24
+ - OAuth2/JWT schemes, bearer/api-key/basic auth, scope-based authorization helpers
25
+ - AI features (distinctive)
26
+ - RAG pipeline (memory backend), LLM instruction generator, MCP exporter
27
+ - Serverless examples (new)
28
+ - Examples for AWS Lambda, Google Cloud Functions, Azure Functions, and Vercel
29
+
30
+ ### Quality gates snapshot
31
+
32
+ - Tests: 643 passing, 55 pending (primarily OAuth2 integration/helpers due to test infra)
33
+ - Coverage: ~67.6% line coverage, ~39.3% branch coverage
34
+ - Build: rspec green locally; CLI flows validated via specs
35
+
36
+ ### Notable gaps and risks
37
+
38
+ 1. Multipart/form-data & file uploads
39
+ - Missing first-class multipart parsing, file validations (size, type), and streaming
40
+ 2. Streaming/SSE/WebSockets
41
+ - No streaming response primitives, SSE helpers, or WebSocket integration
42
+ 3. Rails integration depth
43
+ - Foundational modules and route helpers exist; needs deeper, ergonomic controller wiring
44
+ 4. OAuth2 test infrastructure
45
+ - 55 pending specs rely on external JWT/JWKS/WebMock setup; needs deterministic fixtures
46
+ 5. Request body naming consistency
47
+ - Handlers typically receive JSON under `:body`; align docs/tests (deprecate `:data` alias)
48
+ 6. Documentation drift
49
+ - Some README snippets are truncated or schematic; ensure copy-paste runnable examples
50
+ 7. Performance and budgets
51
+ - No standardized benchmark suite or perf budgets in CI; schema caching hot paths can improve
52
+ 8. API stability and versioning
53
+ - Clarify SemVer guarantees, deprecations policy, and extension points
54
+ 9. Error model consistency
55
+ - Consider standard Problem Details (RFC 7807) responses and uniform error envelopes
56
+
57
+ ### Prioritized improvements (next 4–8 weeks)
58
+
59
+ - P0 – Test & DX hardening (1–2 weeks)
60
+ - Convert OAuth2/JWT specs from pending to passing using local JWKS fixtures/mocks
61
+ - Normalize request body to `inputs[:body]` in docs/tests; add deprecation notice for `:data`
62
+ - Fix/validate README code blocks; add a doc-examples smoke test in CI
63
+ - Raise coverage to ≥75% by adding failure-path tests for DSL, middleware, and generators
64
+
65
+ - P1 – Multipart/form-data + content negotiation (2–3 weeks)
66
+ - Add `multipart_body`, `file_part`, `form_field`, content-type validation, and max-size limits
67
+ - Stream uploads to tempfiles; pluggable validators for MIME/type magic
68
+
69
+ - P2 – Rails deep integration (2–3 weeks)
70
+ - Controller macro to mount endpoints with automatic validation/serialization
71
+ - Error mapping to Rails responders; parameter extraction; generators/scaffolds
72
+
73
+ - P3 – Streaming primitives (3–4 weeks)
74
+ - SSE helper (`.out(stream_body(...))`), chunked responses; foundational WebSocket adapter design
75
+
76
+ - P3 – Performance/observability (parallel, 1–2 weeks)
77
+ - Add microbench suite (endpoint build, request path, serialization); cache compiled schemas
78
+ - Optional OTLP tracing exporter wiring helper and labeled Prometheus metrics out-of-the-box
79
+
80
+ ### ADRs and decision tracking
81
+
82
+ - A new `docs/adr/` directory is in place. Suggested initial ADRs:
83
+ - [ADR-0001: Base class strategy (SinatraRapiTapir) vs manual extension](adr/0001-base-class-strategy.md)
84
+ - [ADR-0002: Type shortcut (T) and type system boundaries](adr/0002-type-shortcut-and-type-system.md)
85
+ - [ADR-0003: OpenAPI source-of-truth and doc generation flow](adr/0003-openapi-source-of-truth.md)
86
+ - [ADR-0004: Client generation target (TypeScript first) and interface conventions](adr/0004-client-generation-typescript-first.md)
87
+ - [ADR-0005: Authentication architecture (schemes + helpers + middleware)](adr/0005-auth-architecture.md)
88
+ - [ADR-0006: Observability defaults (health, logging, metrics/tracing hooks)](adr/0006-observability-defaults.md)
89
+ - [ADR-0007: AI features scope (RAG/LLM/MCP) and maintainability boundaries](adr/0007-ai-scope-and-boundaries.md)
90
+
91
+ The remainder of this document preserves the original blueprint for historical context and broader roadmap.
4
92
 
5
93
  ## Repository Structure
6
94
 
@@ -414,7 +502,7 @@ Tapir::Docs::SwaggerUI.mount(openapi_spec, path: "/docs")
414
502
  ### Technical Metrics
415
503
  - **Performance**: < 1ms overhead for simple endpoints
416
504
  - **Memory**: < 10MB memory overhead for typical applications
417
- - **Compatibility**: Support for Ruby 3.1+ and all major frameworks
505
+ - **Compatibility**: Support for Ruby 3.3+ and all major frameworks
418
506
  - **Coverage**: > 95% test coverage across all components
419
507
 
420
508
  ### Developer Experience Metrics
@@ -288,7 +288,7 @@ endpoint
288
288
  ### **Technical Metrics**
289
289
  - ✅ **Performance**: < 1ms overhead achieved in benchmarks
290
290
  - ✅ **Memory**: < 10MB overhead in typical applications
291
- - ✅ **Compatibility**: Ruby 3.1+ support with framework compatibility
291
+ - ✅ **Compatibility**: Ruby 3.3+ support with framework compatibility
292
292
  - ✅ **Coverage**: 70.4% coverage (target >95% for future releases)
293
293
 
294
294
  ### **Developer Experience Metrics**
@@ -1,163 +1,94 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # This file demonstrates the improved auto-derivation capabilities that work
4
- # well with Ruby's dynamic nature and lack of built-in type declarations
3
+ # This file demonstrates the auto-derivation capabilities of RapiTapir's type
4
+ # system, working well with Ruby's dynamic nature and lack of built-in type
5
+ # declarations.
5
6
 
6
7
  require_relative '../lib/rapitapir/types'
7
8
 
8
- puts "=== RapiTapir Auto-Derivation Examples ==="
9
+ puts '=== RapiTapir Auto-Derivation Examples ==='
9
10
  puts
10
11
 
11
12
  # 1. From Hash (most reliable for Ruby)
12
- puts "1. From Hash (recommended for Ruby)"
13
+ puts '1. From Hash (recommended for Ruby)'
13
14
  hash_data = {
14
- name: "John Doe",
15
+ name: 'John Doe',
15
16
  age: 30,
16
- email: "john@example.com",
17
+ email: 'john@example.com',
17
18
  active: true,
18
19
  score: 95.5,
19
- tags: ["developer", "ruby"],
20
- metadata: { role: "senior", team: "backend" }
20
+ tags: ['developer', 'ruby'],
21
+ metadata: { role: 'senior', team: 'backend' }
21
22
  }
22
23
 
23
24
  schema = RapiTapir::Types.from_hash(hash_data)
24
- puts "Schema from hash:"
25
+ puts 'Schema from hash:'
25
26
  puts schema.field_types.inspect
26
27
  puts
27
28
 
28
29
  # 2. From Hash with filtering
30
+ puts '2. From Hash with filtering'
29
31
  filtered_schema = RapiTapir::Types.from_hash(hash_data, except: [:metadata])
30
32
  puts "Schema with 'except' filtering:"
31
33
  puts filtered_schema.field_types.inspect
32
34
  puts
33
35
 
34
- # 3. From explicit types (recommended for classes)
35
- puts "2. From Class with Explicit Types (recommended)"
36
- class Person
37
- attr_accessor :name, :age, :email, :active
38
- end
39
-
40
- # Method 1: Via types parameter
41
- person_schema = RapiTapir::Types.from_object(Person, types: {
42
- name: :string,
43
- age: :integer,
44
- email: :string,
45
- active: :boolean
46
- })
47
- puts "Person schema with explicit types:"
48
- puts person_schema.field_types.inspect
49
- puts
50
-
51
- # 4. From instance (less reliable but convenient)
52
- puts "3. From Instance (use with well-populated data)"
53
- person = Person.new
54
- person.name = "Jane Smith"
55
- person.age = 28
56
- person.email = "jane@example.com"
57
- person.active = true
58
-
59
- instance_schema = RapiTapir::Types.from_object(person)
60
- puts "Schema from instance:"
61
- puts instance_schema.field_types.inspect
36
+ filtered_only = RapiTapir::Types.from_hash(hash_data, only: [:name, :email])
37
+ puts "Schema with 'only' filtering:"
38
+ puts filtered_only.field_types.inspect
62
39
  puts
63
40
 
64
- # 5. From Struct (good compromise)
65
- puts "4. From Struct (good Ruby pattern)"
66
- Point = Struct.new(:x, :y, :z) do
67
- def distance_from_origin
68
- Math.sqrt(x**2 + y**2 + z**2)
69
- end
70
- end
71
-
72
- sample_point = Point.new(1.0, 2.0, 3.0)
73
- point_schema = RapiTapir::Types.from_object(Point, sample: sample_point)
74
- puts "Point schema from Struct:"
75
- puts point_schema.field_types.inspect
76
- puts
77
-
78
- # 6. DSL approach (most Ruby-like)
79
- puts "5. DSL Approach (Ruby-idiomatic)"
80
- class User
81
- include RapiTapir::Types::AutoDerivation::Annotated
82
-
83
- attr_accessor :username, :email, :age, :admin
84
-
85
- rapitapir_schema do
86
- field :username, :string
87
- field :email, :string
88
- field :age, :integer
89
- field :admin, :boolean
90
- end
91
- end
92
-
93
- user_schema = RapiTapir::Types.from_object(User)
94
- puts "User schema with DSL:"
95
- puts user_schema.field_types.inspect
96
- puts
97
-
98
- # 7. OpenStruct (convenient for prototyping)
99
- puts "6. From OpenStruct"
41
+ # 3. OpenStruct (convenient for prototyping)
42
+ puts '3. From OpenStruct'
100
43
  require 'ostruct'
101
44
 
102
45
  config = OpenStruct.new(
103
- host: "localhost",
46
+ host: 'localhost',
104
47
  port: 3000,
105
48
  ssl: false,
106
49
  timeout: 30.5
107
50
  )
108
51
 
109
52
  config_schema = RapiTapir::Types.from_open_struct(config)
110
- puts "Config schema from OpenStruct:"
53
+ puts 'Config schema from OpenStruct:'
111
54
  puts config_schema.field_types.inspect
112
55
  puts
113
56
 
114
- # 8. JSON Schema (for external APIs)
115
- puts "7. From JSON Schema"
57
+ # 4. JSON Schema (for external APIs)
58
+ puts '4. From JSON Schema'
116
59
  json_schema = {
117
- "type" => "object",
118
- "properties" => {
119
- "id" => { "type" => "integer" },
120
- "name" => { "type" => "string", "maxLength" => 100 },
121
- "email" => { "type" => "string", "format" => "email" },
122
- "created_at" => { "type" => "string", "format" => "date-time" },
123
- "tags" => {
124
- "type" => "array",
125
- "items" => { "type" => "string" }
60
+ 'type' => 'object',
61
+ 'properties' => {
62
+ 'id' => { 'type' => 'integer' },
63
+ 'name' => { 'type' => 'string', 'maxLength' => 100 },
64
+ 'email' => { 'type' => 'string', 'format' => 'email' },
65
+ 'created_at' => { 'type' => 'string', 'format' => 'date-time' },
66
+ 'tags' => {
67
+ 'type' => 'array',
68
+ 'items' => { 'type' => 'string' }
126
69
  }
127
70
  },
128
- "required" => ["id", "name", "email"]
71
+ 'required' => ['id', 'name', 'email']
129
72
  }
130
73
 
131
74
  json_derived_schema = RapiTapir::Types.from_json_schema(json_schema)
132
- puts "Schema from JSON Schema:"
75
+ puts 'Schema from JSON Schema:'
133
76
  puts json_derived_schema.field_types.inspect
134
77
  puts
135
78
 
136
- # 9. Demonstrate the limitations
137
- puts "8. Limitations and Error Handling"
138
-
139
- class EmptyClass
140
- end
141
-
79
+ # 5. Protobuf (when available)
80
+ puts '5. From Protobuf (if a protobuf descriptor is available)'
142
81
  begin
143
- # This should fail gracefully
144
- RapiTapir::Types.from_object(EmptyClass)
145
- rescue ArgumentError => e
146
- puts "Expected error for empty class: #{e.message}"
82
+ require 'google/protobuf' # rubocop:disable Lint/RequireRelativeSelfPath
83
+ puts ' google-protobuf is available — from_protobuf(Descriptor) is supported'
84
+ rescue LoadError
85
+ puts ' google-protobuf not installed — from_protobuf is available once it is'
147
86
  end
148
-
149
- begin
150
- # This should also fail
151
- RapiTapir::Types.from_object(Point) # Struct without sample
152
- rescue ArgumentError => e
153
- puts "Expected error for Struct without sample: #{e.message}"
154
- end
155
-
156
87
  puts
157
- puts "=== Recommendations ==="
158
- puts "1. Use from_hash() for parsed JSON or config data"
159
- puts "2. Use explicit types parameter for Ruby classes"
160
- puts "3. Use DSL annotations for reusable schemas"
161
- puts "4. Use Structs for value objects with samples"
162
- puts "5. Use from_json_schema() for external API integration"
163
- puts "6. Avoid deriving from empty classes or nil values"
88
+
89
+ puts '=== Recommendations ==='
90
+ puts '1. Use from_hash() for parsed JSON or config data'
91
+ puts '2. Use from_open_struct() for prototyping'
92
+ puts '3. Use from_json_schema() for external API integration'
93
+ puts '4. Use from_protobuf() when wrapping protobuf messages'
94
+ puts '5. Avoid deriving from empty hashes or nil values'
@@ -1,56 +1,83 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Add the lib directory to the load path
4
- lib_path = File.expand_path('../lib', __dir__)
5
- $LOAD_PATH.unshift(lib_path) unless $LOAD_PATH.include?(lib_path)
3
+ require_relative '../../lib/rapitapir'
6
4
 
7
- require 'rapitapir'
5
+ USER_TYPE = RapiTapir::Types.hash({
6
+ 'id' => RapiTapir::Types.integer,
7
+ 'name' => RapiTapir::Types.string,
8
+ 'email' => RapiTapir::Types.string
9
+ })
8
10
 
9
- # Include DSL to use helper methods
10
- include RapiTapir::DSL
11
+ USER_FULL_TYPE = RapiTapir::Types.hash({
12
+ 'id' => RapiTapir::Types.integer,
13
+ 'name' => RapiTapir::Types.string,
14
+ 'email' => RapiTapir::Types.string,
15
+ 'created_at' => RapiTapir::Types.string
16
+ })
17
+
18
+ CREATE_USER_TYPE = RapiTapir::Types.hash({
19
+ 'name' => RapiTapir::Types.string,
20
+ 'email' => RapiTapir::Types.string,
21
+ 'password' => RapiTapir::Types.string
22
+ })
23
+
24
+ ERROR_TYPE = RapiTapir::Types.hash({
25
+ 'error' => RapiTapir::Types.string,
26
+ 'message' => RapiTapir::Types.string
27
+ })
28
+
29
+ VALIDATION_ERROR_TYPE = RapiTapir::Types.hash({
30
+ 'error' => RapiTapir::Types.string,
31
+ 'validation_errors' => RapiTapir::Types.array(RapiTapir::Types.string)
32
+ })
11
33
 
12
34
  # Define endpoints for CLI usage
13
- [
35
+ user_api_endpoints = [
14
36
  # Get all users
15
37
  RapiTapir.get('/users')
16
- .out(json_body([{ id: :integer, name: :string, email: :string }]))
38
+ .ok(RapiTapir::Types.array(USER_TYPE))
17
39
  .summary('Get all users')
18
- .description('Retrieve a list of all users'),
40
+ .description('Retrieve a list of all users')
41
+ .build,
19
42
 
20
43
  # Get user by ID
21
44
  RapiTapir.get('/users/:id')
22
- .in(path_param(:id, :integer))
23
- .out(json_body({ id: :integer, name: :string, email: :string }))
45
+ .path_param(:id, RapiTapir::Types.integer)
46
+ .ok(USER_FULL_TYPE)
47
+ .not_found(ERROR_TYPE)
24
48
  .summary('Get user by ID')
25
- .description('Retrieve a specific user by their ID'),
49
+ .description('Retrieve a specific user by their ID')
50
+ .build,
26
51
 
27
- # Create new user
52
+ # Create a new user
28
53
  RapiTapir.post('/users')
29
- .in(body({ name: :string, email: :string }))
30
- .out(json_body({ id: :integer, name: :string, email: :string }))
31
- .summary('Create new user')
32
- .description('Create a new user with the provided information'),
54
+ .json_body(CREATE_USER_TYPE)
55
+ .created(USER_TYPE)
56
+ .bad_request(VALIDATION_ERROR_TYPE)
57
+ .summary('Create a new user')
58
+ .description('Create a new user account')
59
+ .build,
33
60
 
34
- # Update user
61
+ # Update a user
35
62
  RapiTapir.put('/users/:id')
36
- .in(path_param(:id, :integer))
37
- .in(body({ name: :string, email: :string }))
38
- .out(json_body({ id: :integer, name: :string, email: :string }))
39
- .summary('Update user')
40
- .description('Update an existing user'),
63
+ .path_param(:id, RapiTapir::Types.integer)
64
+ .json_body(RapiTapir::Types.hash({
65
+ 'name' => RapiTapir::Types.string,
66
+ 'email' => RapiTapir::Types.string
67
+ }))
68
+ .ok(USER_FULL_TYPE)
69
+ .not_found(ERROR_TYPE)
70
+ .bad_request(VALIDATION_ERROR_TYPE)
71
+ .summary('Update a user')
72
+ .description('Update an existing user')
73
+ .build,
41
74
 
42
- # Delete user
75
+ # Delete a user
43
76
  RapiTapir.delete('/users/:id')
44
- .in(path_param(:id, :integer))
45
- .out(json_body({ success: :boolean }))
46
- .summary('Delete user')
47
- .description('Delete a user by their ID'),
48
-
49
- # Search users
50
- RapiTapir.get('/users/search')
51
- .in(query(:q, :string))
52
- .in(query(:limit, :integer, optional: true))
53
- .out(json_body([{ id: :integer, name: :string, email: :string }]))
54
- .summary('Search users')
55
- .description('Search for users by name or email')
77
+ .path_param(:id, RapiTapir::Types.integer)
78
+ .no_content
79
+ .not_found(ERROR_TYPE)
80
+ .summary('Delete a user')
81
+ .description('Permanently delete a user account')
82
+ .build
56
83
  ]
data/examples/demo_api.rb CHANGED
@@ -1,41 +1,80 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require_relative 'lib/rapitapir'
4
- include RapiTapir::DSL
3
+ require_relative '../lib/rapitapir'
4
+
5
+ # Type definitions
6
+ USER_TYPE = RapiTapir::Types.hash({
7
+ 'id' => RapiTapir::Types.integer,
8
+ 'name' => RapiTapir::Types.string,
9
+ 'email' => RapiTapir::Types.string
10
+ })
11
+
12
+ USER_FULL_TYPE = RapiTapir::Types.hash({
13
+ 'id' => RapiTapir::Types.integer,
14
+ 'name' => RapiTapir::Types.string,
15
+ 'email' => RapiTapir::Types.string,
16
+ 'created_at' => RapiTapir::Types.string
17
+ })
18
+
19
+ CREATE_USER_TYPE = RapiTapir::Types.hash({
20
+ 'name' => RapiTapir::Types.string,
21
+ 'email' => RapiTapir::Types.string,
22
+ 'password' => RapiTapir::Types.string
23
+ })
24
+
25
+ ERROR_TYPE = RapiTapir::Types.hash({
26
+ 'error' => RapiTapir::Types.string,
27
+ 'message' => RapiTapir::Types.string
28
+ })
29
+
30
+ VALIDATION_ERROR_TYPE = RapiTapir::Types.hash({
31
+ 'error' => RapiTapir::Types.string,
32
+ 'validation_errors' => RapiTapir::Types.array(RapiTapir::Types.string)
33
+ })
5
34
 
6
35
  # Sample API endpoints for demonstration
7
36
  RapiTapir.get('/users')
8
- .out(json_body([{ id: :integer, name: :string, email: :string }]))
37
+ .ok(RapiTapir::Types.array(USER_TYPE))
9
38
  .summary('List all users')
10
39
  .description('Retrieve a paginated list of all users in the system')
40
+ .build
11
41
 
12
42
  RapiTapir.get('/users/:id')
13
- .in(path_param(:id, :integer))
14
- .out(json_body({ id: :integer, name: :string, email: :string, created_at: :string }))
15
- .error_out(404, json_body({ error: :string, message: :string }))
43
+ .path_param(:id, RapiTapir::Types.integer)
44
+ .ok(USER_FULL_TYPE)
45
+ .not_found(ERROR_TYPE)
16
46
  .summary('Get user by ID')
17
47
  .description('Retrieve detailed information about a specific user')
48
+ .build
18
49
 
19
50
  RapiTapir.post('/users')
20
- .in(json_body({ name: :string, email: :string, password: :string }))
21
- .out(status_code(201), json_body({ id: :integer, name: :string, email: :string }))
22
- .error_out(400, json_body({ error: :string, validation_errors: [:string] }))
23
- .error_out(422, json_body({ error: :string, message: :string }))
51
+ .json_body(CREATE_USER_TYPE)
52
+ .created(USER_TYPE)
53
+ .bad_request(VALIDATION_ERROR_TYPE)
54
+ .unprocessable_entity(ERROR_TYPE)
24
55
  .summary('Create new user')
25
56
  .description('Create a new user account with the provided information')
57
+ .build
26
58
 
27
59
  RapiTapir.put('/users/:id')
28
- .in(path_param(:id, :integer))
29
- .in(json_body({ name: :string, email: :string }))
30
- .out(json_body({ id: :integer, name: :string, email: :string, updated_at: :string }))
31
- .error_out(404, json_body({ error: :string, message: :string }))
32
- .error_out(400, json_body({ error: :string, validation_errors: [:string] }))
60
+ .path_param(:id, RapiTapir::Types.integer)
61
+ .json_body(RapiTapir::Types.hash({
62
+ 'name' => RapiTapir::Types.string,
63
+ 'email' => RapiTapir::Types.string
64
+ }))
65
+ .ok(USER_FULL_TYPE)
66
+ .not_found(ERROR_TYPE)
67
+ .bad_request(VALIDATION_ERROR_TYPE)
33
68
  .summary('Update user')
34
69
  .description('Update an existing user with new information')
70
+ .build
35
71
 
36
72
  RapiTapir.delete('/users/:id')
37
- .in(path_param(:id, :integer))
38
- .out(status_code(204))
39
- .error_out(404, json_body({ error: :string, message: :string }))
73
+ .path_param(:id, RapiTapir::Types.integer)
74
+ .no_content
75
+ .not_found(ERROR_TYPE)
40
76
  .summary('Delete user')
41
77
  .description('Permanently delete a user account')
78
+ .build
79
+
80
+ puts "✅ Defined #{RapiTapir.endpoints.size} endpoints"
@@ -135,21 +135,21 @@ if SINATRA_AVAILABLE
135
135
  server(url: 'https://api.example.com', description: 'Production server')
136
136
 
137
137
  # Authentication configuration
138
- bearer_auth(:bearer, {
139
- realm: 'Enterprise Task Management API',
140
- token_validator: proc do |token|
141
- user = UserDatabase.find_by_token(token)
142
- next nil unless user
143
-
144
- {
145
- user: user,
146
- scopes: user[:scopes]
147
- }
148
- end
149
- })
138
+ add_auth_scheme(:bearer, RapiTapir::Auth.bearer_token(:bearer, {
139
+ realm: 'Enterprise Task Management API',
140
+ token_validator: proc do |token|
141
+ user = UserDatabase.find_by_token(token)
142
+ next nil unless user
143
+
144
+ {
145
+ user: user,
146
+ scopes: user[:scopes]
147
+ }
148
+ end
149
+ }))
150
150
 
151
151
  # Middleware configuration based on environment
152
- if development?
152
+ if Sinatra::Base.environment == :development
153
153
  development_defaults!
154
154
  else
155
155
  production_defaults!