Class: OpenapiFirst::Middlewares::RequestValidation
- Inherits:
-
Object
- Object
- OpenapiFirst::Middlewares::RequestValidation
- Defined in:
- lib/openapi_first/middlewares/request_validation.rb
Overview
A Rack middleware to validate requests against an OpenAPI API description. All error responses can be customized via the error_response: option.
Request body validation
-
Returns
415if the request content-type does not match the OpenAPI description. -
Returns
400for invalid JSON, missing required fields, type/enum/schema violations, orreadOnlyfields. -
Empty bodies are accepted when the body is optional in the spec.
Parameter validation
Query, path, header, and cookie parameters are validated and type-converted against the spec. Missing required parameters or type/format violations return 400.
Instance Attribute Summary collapse
- #app ⇒ Object readonly
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, spec = nil, options = {}) ⇒ RequestValidation
constructor
A new instance of RequestValidation.
Constructor Details
#initialize(app, spec = nil, options = {}) ⇒ RequestValidation
Returns a new instance of RequestValidation.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/openapi_first/middlewares/request_validation.rb', line 33 def initialize(app, spec = nil, = {}) @app = app if spec.is_a?(Hash) = spec spec = [:spec] end @raise = .fetch(:raise_error, OpenapiFirst.configuration.request_validation_raise_error) @error_response_class = error_response_option([:error_response]) spec ||= :default spec = OpenapiFirst[spec] if spec.is_a?(Symbol) @definition = spec.is_a?(Definition) ? spec : OpenapiFirst.load(spec) end |
Instance Attribute Details
#app ⇒ Object (readonly)
49 50 51 |
# File 'lib/openapi_first/middlewares/request_validation.rb', line 49 def app @app end |
Instance Method Details
#call(env) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/openapi_first/middlewares/request_validation.rb', line 51 def call(env) rack_response = nil app_called = false validated = @definition.validate_request(Rack::Request.new(env), raise_error: @raise) do |v| app_called = true env[REQUEST] = v rack_response = @app.call(env) end env[REQUEST] = validated failure = validated.error return @error_response_class.new(failure:).render if failure && @error_response_class return rack_response if app_called @app.call(env) end |