diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..44e9e40 --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ +.DS_Store + +# rspec failure tracking +.rspec_status + +# rubocop cache of remote rules file +.rubocop-https---dev-k-io-rubocop-* + +*.gem diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..13fc79b --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,27 @@ +inherit_from: + - https://dev.k.io/rubocop/rubocop.yml + +AllCops: + TargetRubyVersion: 2.7 + Exclude: + - Rakefile + - "bin/**/*" + +# Always use double quotes +Style/StringLiterals: + EnforcedStyle: double_quotes + +Style/Documentation: + Enabled: false + +Metrics/CyclomaticComplexity: + Enabled: false + +Metrics/PerceivedComplexity: + Enabled: false + +Metrics/AbcSize: + Enabled: false + +Metrics/MethodLength: + Max: 50 diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..be94e6f --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.2.2 diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..1ce0a14 --- /dev/null +++ b/Gemfile @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in apia-open_api.gemspec +gemspec + +gem "rake", "~> 13.0" + +gem "rspec", "~> 3.0" + +gem "rubocop", "~> 1.21" + +gem "apia", "~> 3.5" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..8859b1f --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,76 @@ +PATH + remote: . + specs: + apia-open_api (0.1.0) + activesupport (>= 6) + +GEM + remote: https://rubygems.org/ + specs: + activesupport (7.0.6) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + apia (3.5.0) + json + rack + ast (2.4.2) + concurrent-ruby (1.2.2) + diff-lcs (1.5.0) + i18n (1.14.1) + concurrent-ruby (~> 1.0) + json (2.6.3) + minitest (5.20.0) + parallel (1.23.0) + parser (3.2.2.3) + ast (~> 2.4.1) + racc + racc (1.7.1) + rack (3.0.8) + rainbow (3.1.1) + rake (13.0.6) + regexp_parser (2.8.1) + rexml (3.2.6) + rspec (3.12.0) + rspec-core (~> 3.12.0) + rspec-expectations (~> 3.12.0) + rspec-mocks (~> 3.12.0) + rspec-core (3.12.2) + rspec-support (~> 3.12.0) + rspec-expectations (3.12.3) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-mocks (3.12.6) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.12.0) + rspec-support (3.12.1) + rubocop (1.52.0) + json (~> 2.3) + parallel (~> 1.10) + parser (>= 3.2.0.0) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.28.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.29.0) + parser (>= 3.2.1.0) + ruby-progressbar (1.13.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (2.4.2) + +PLATFORMS + arm64-darwin-22 + +DEPENDENCIES + apia (~> 3.5) + apia-open_api! + rake (~> 13.0) + rspec (~> 3.0) + rubocop (~> 1.21) + +BUNDLED WITH + 2.4.19 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..08a83a2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2023 Krystal Hosting Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md index 4d21dcc..1ade41d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,96 @@ # Apia OpenAPI Specification This gem can generate an [OpenAPI](https://www.openapis.org/) compatible schema from an API implemented using [Apia](https://github.com/krystal/apia). + +## Installation + +TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org. + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG + +## Usage + +The schema can be mounted in much the same way as an [Apia API](https://github.com/krystal/apia) itself. + +For example, for a Ruby on Rails application: + +```ruby +module MyApp + class Application < Rails::Application + + config.middleware.use Apia::OpenApi::Rack, + api_class: "CoreAPI::Base", + schema_path: "/core/v1/schema/openapi.json", + base_url: "http://katapult-api.localhost/core/v1" + + end +end +``` + +Where `CoreAPI::Base` is the name of the API class that inherits from `Apia::API`. + +## Generating a client library from the spec + +It's possible to generate a client library from the generated OpenAPI schema using [OpenAPI Generator](https://openapi-generator.tech/). + +For example we can generate a Ruby client with the following: + +```bash +brew install openapi-generator +openapi-generator generate -i openapi.json -g ruby -o openapi-client --additional-properties=gemName=myapp-openapi-client,moduleName=MyAppOpenAPIClient +``` + +The generated client will be in the `openapi-client` directory and will contain a readme with instructions on how to use it. + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. + +In `/examples` there is an example Apia API application that can be used to try out the gem. + +Run `rackup` from the root of `/examples` to start the [rack app](https://github.com/rack/rack) running the example API. +To view the generated OpenAPI schema, visit: http://127.0.0.1:9292/core/v1/schema/openapi.json +`/examples/config.ru` shows how to mount the schema endpoint. + +The generated schema can be viewed, validated and tried out using the online [Swagger Editor](https://editor.swagger.io/). You'll need to add the bearer token to the swagger editor to authenticate the requests. After that, they should work as expected. The bearer token is defined in main_authenticator.rb. + +Currently the online swagger-editor only allows the OpenAPI schema v3.0.0. But it's also possible to run the swagger-editor locally, which allows us to check against v3.1.0. + +e.g with this docker-compose.yml file: + +```yml +version: "3.3" +services: + swagger-editor: + image: swaggerapi/swagger-editor:next-v5 + container_name: "swagger-editor" + ports: + - "8081:80" +``` + +Run `docker-compose up` and visit http://localhost:8081 to view the swagger editor. + +### Tests and Linting + +- `bin/rspec` +- `bin/rubocop` + +You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +## Releasing a new version + +TODO: Write instructions for releasing a new version of the gem. + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/krystal/apia-open_api. + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..cca7175 --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rspec/core/rake_task" + +RSpec::Core::RakeTask.new(:spec) + +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[spec rubocop] diff --git a/apia-open_api.gemspec b/apia-open_api.gemspec new file mode 100644 index 0000000..9e6ece4 --- /dev/null +++ b/apia-open_api.gemspec @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +require_relative "lib/apia/open_api/version" + +Gem::Specification.new do |spec| + spec.name = "apia-open_api" + spec.version = Apia::OpenApi::VERSION + spec.authors = ["Paul Sturgess"] + + spec.summary = "Apia OpenAPI spec generator" + spec.homepage = "https://github.com/krystal/apia-openapi" + spec.license = "MIT" + spec.required_ruby_version = ">= 2.7.0" + + spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = "https://github.com/krystal/apia-openapi" + spec.metadata["changelog_uri"] = "https://github.com/krystal/apia-openapi/changelog.md" + + spec.metadata["rubygems_mfa_required"] = "true" + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + spec.files = Dir.chdir(__dir__) do + `git ls-files -z`.split("\x0").reject do |f| + (File.expand_path(f) == __FILE__) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(/\Aexe\//) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + spec.add_dependency "activesupport", ">= 6" +end diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..ba81268 --- /dev/null +++ b/bin/console @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "apia/open_api" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +require "irb" +IRB.start(__FILE__) diff --git a/bin/rspec b/bin/rspec new file mode 100755 index 0000000..cb53ebe --- /dev/null +++ b/bin/rspec @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rspec' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rspec-core", "rspec") diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 0000000..369a05b --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'rubocop' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 0000000..d341e92 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,5 @@ +# Apia Example + +This directory contains an example application which can be used to try out this gem. + +Refer to the main readme for more information on how to run it. diff --git a/examples/config.ru b/examples/config.ru new file mode 100644 index 0000000..a759910 --- /dev/null +++ b/examples/config.ru @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +# Uncomment the following if you need to use a local version of the Apia gem +require "bundler/inline" +gemfile do + gem "rack", "2.2.8" + gem "apia", path: "../../apia" + gem "activesupport" + gem "puma" + gem "pry" +end + +$LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) +$LOAD_PATH.unshift(File.expand_path(__dir__)) + +require "apia" +require "apia/rack" +require "apia/open_api" +require "core_api/base" + +use Apia::OpenApi::Rack, + api_class: "CoreAPI::Base", + schema_path: "/core/v1/schema/openapi.json", + base_url: "http://127.0.0.1:9292/core/v1/" +use Apia::Rack, CoreAPI::Base, "/core/v1", development: true + +app = proc do + [400, { "Content-Type" => "text/plain" }, + ["Apia Example API Server. Make a request to a an example API for example /core/v1."]] +end + +run app diff --git a/examples/core_api/argument_sets/object_lookup.rb b/examples/core_api/argument_sets/object_lookup.rb new file mode 100644 index 0000000..3e49c2b --- /dev/null +++ b/examples/core_api/argument_sets/object_lookup.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module CoreAPI + module ArgumentSets + class ObjectLookup < Apia::LookupArgumentSet + + name "Object Lookup" + description "Provides for objects to be looked up" + + argument :id, type: :string + argument :permalink, type: :string + + potential_error "ObjectNotFound" do + code :object_not_found + description "No object was found matching any of the criteria provided in the arguments" + http_status 404 + end + + resolver do |set, _request, _scope| + objects = [{ id: "123", permalink: "perma-123" }] + object = objects.find { |o| o[:id] == set[:id] || o[:permalink] == set[:permalink] } + raise_error "ObjectNotFound" if object.nil? + + object + end + + end + end +end diff --git a/examples/core_api/argument_sets/time_lookup_argument_set.rb b/examples/core_api/argument_sets/time_lookup_argument_set.rb new file mode 100644 index 0000000..a7a1a68 --- /dev/null +++ b/examples/core_api/argument_sets/time_lookup_argument_set.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module CoreAPI + module ArgumentSets + class TimeLookupArgumentSet < Apia::LookupArgumentSet + + argument :unix, type: :string + argument :string, type: :string + + potential_error "InvalidTime" do + code :invalid_time + http_status 400 + end + + def resolve + if self[:unix] + Time.at(self[:unix].to_i) + elsif self[:string] + begin + Time.parse(self[:string]) + rescue ArgumentError + raise_error "InvalidTime" + end + end + end + + end + end +end diff --git a/examples/core_api/base.rb b/examples/core_api/base.rb new file mode 100644 index 0000000..3a818e5 --- /dev/null +++ b/examples/core_api/base.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +require "core_api/main_authenticator" +require "core_api/controllers/time_controller" +require "core_api/endpoints/test_endpoint" + +module CoreAPI + class Base < Apia::API + + authenticator MainAuthenticator + + scopes do + add "time", "Allows time telling functions" + end + + routes do + schema + + get "example/format", controller: Controllers::TimeController, endpoint: :format + post "example/format", controller: Controllers::TimeController, endpoint: :format + post "example/format_multiple", controller: Controllers::TimeController, endpoint: :format_multiple + + group :time do + name "Time functions" + description "Everything related to time elements" + get "time/now", endpoint: Endpoints::TimeNowEndpoint + post "time/now", endpoint: Endpoints::TimeNowEndpoint + + get "test/:object", endpoint: Endpoints::TestEndpoint + post "test/:object", endpoint: Endpoints::TestEndpoint + + group :formatting do + name "Formatting" + controller Controllers::TimeController + + get "time/formatting/format", endpoint: :format + post "time/formatting/format", endpoint: :format + end + end + end + + end +end diff --git a/examples/core_api/controllers/time_controller.rb b/examples/core_api/controllers/time_controller.rb new file mode 100644 index 0000000..fd2cefd --- /dev/null +++ b/examples/core_api/controllers/time_controller.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require "core_api/objects/time" +require "core_api/argument_sets/time_lookup_argument_set" +require "core_api/endpoints/time_now_endpoint" + +module CoreAPI + module Controllers + class TimeController < Apia::Controller + + name "Time API" + description "Returns the time in varying ways" + + endpoint :now, Endpoints::TimeNowEndpoint + + # TODO: add example of multiple objects using the same objects, to ensure + # we are handing circular references correctly + endpoint :format do + description "Format the given time" + argument :time, type: ArgumentSets::TimeLookupArgumentSet, required: true + argument :timezone, type: Objects::TimeZone + field :formatted_time, type: :string + action do + time = request.arguments[:time] + response.add_field :formatted_time, time.resolve.to_s + end + end + + endpoint :format_multiple do + description "Format the given times" + argument :times, type: [ArgumentSets::TimeLookupArgumentSet], required: true + field :formatted_times, type: [:string] + field :times, type: [Objects::Time], include: "unix,year[as_string],as_array_of_objects[as_integer]" + action do + times = [] + request.arguments[:times].each do |time| + times << time.resolve + end + response.add_field :formatted_times, times.map(&:to_s).join(", ") + response.add_field :times, times + end + end + + end + end +end diff --git a/examples/core_api/endpoints/test_endpoint.rb b/examples/core_api/endpoints/test_endpoint.rb new file mode 100644 index 0000000..d024e5e --- /dev/null +++ b/examples/core_api/endpoints/test_endpoint.rb @@ -0,0 +1,35 @@ +# frozen_string_literal: true + +require "core_api/argument_sets/object_lookup" + +module CoreAPI + module Endpoints + class TestEndpoint < Apia::Endpoint + + description "Returns the current time" + argument :object, type: ArgumentSets::ObjectLookup, required: true + field :time, type: Objects::Time, include: "unix,day_of_week,year[as_string]", null: true do + condition do |o| + o[:time].year.to_s == "2023" + end + end + field :object_id, type: :string do + backend { |o| o[:object_id][:id] } + end + scope "time" + + def call + object = request.arguments[:object].resolve + response.add_field :time, get_time_now + response.add_field :object_id, object + end + + private + + def get_time_now + Time.now + end + + end + end +end diff --git a/examples/core_api/endpoints/time_now_endpoint.rb b/examples/core_api/endpoints/time_now_endpoint.rb new file mode 100644 index 0000000..797c4ec --- /dev/null +++ b/examples/core_api/endpoints/time_now_endpoint.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require "core_api/objects/time_zone" + +module CoreAPI + module Endpoints + class TimeNowEndpoint < Apia::Endpoint + + description "Returns the current time" + argument :timezone, type: Objects::TimeZone + argument :time_zones, [Objects::TimeZone] + argument :filters, [:string] + field :time, type: Objects::Time + field :time_zones, type: [Objects::TimeZone] + field :filters, [:string] + field :my_polymorph, type: Objects::MonthPolymorph + scope "time" + + def call + response.add_field :time, get_time_now + response.add_field :filters, request.arguments[:filters] + response.add_field :time_zones, request.arguments[:time_zones] + response.add_field :my_polymorph, get_time_now + end + + private + + def get_time_now + Time.now + end + + end + end +end diff --git a/examples/core_api/main_authenticator.rb b/examples/core_api/main_authenticator.rb new file mode 100644 index 0000000..5a61e6e --- /dev/null +++ b/examples/core_api/main_authenticator.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +module CoreAPI + class MainAuthenticator < Apia::Authenticator + + BEARER_TOKEN = "example" + + type :bearer + + potential_error "InvalidToken" do + code :invalid_token + description "The token provided is invalid. In this example, you should provide '#{BEARER_TOKEN}'." + http_status 403 + + field :given_token, type: :string + end + + def call + configure_cors_response + return if request.options? + + given_token = request.headers["authorization"]&.sub(/\ABearer /, "") + if given_token == BEARER_TOKEN + request.identity = { name: "Example User", id: 1234 } + else + raise_error "CoreAPI/MainAuthenticator/InvalidToken", given_token: given_token.to_s + end + end + + private + + # These are not strictly required, but it allows the app to work with swagger-ui. + def configure_cors_response + # Define a list of cors methods that are permitted for the request. + cors.methods = %w[GET POST PUT PATCH DELETE OPTIONS] + + # Define a list of cors headers that are permitted for the request. + cors.headers = %w[Authorization Content-Type] # or allow all with '*' + + # Define a the hostname to allow for CORS requests. + cors.origin = "*" # or 'example.com' + end + + end +end diff --git a/examples/core_api/objects/day.rb b/examples/core_api/objects/day.rb new file mode 100644 index 0000000..700676a --- /dev/null +++ b/examples/core_api/objects/day.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +module CoreAPI + module Objects + class Day < Apia::Enum + + value "Sunday" + value "Monday" + value "Tuesday" + value "Wednesday" + value "Thursday" + value "Friday" + value "Saturday" + + end + end +end diff --git a/examples/core_api/objects/month_long.rb b/examples/core_api/objects/month_long.rb new file mode 100644 index 0000000..ba42e60 --- /dev/null +++ b/examples/core_api/objects/month_long.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module CoreAPI + module Objects + class MonthLong < Apia::Object + + description "Represents a month" + + field :month_long, type: :string do + backend { |t| t.strftime("%B") } + end + + end + end +end diff --git a/examples/core_api/objects/month_polymorph.rb b/examples/core_api/objects/month_polymorph.rb new file mode 100644 index 0000000..db1f4d4 --- /dev/null +++ b/examples/core_api/objects/month_polymorph.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +require "core_api/objects/month_long" +require "core_api/objects/month_short" + +module CoreAPI + module Objects + class MonthPolymorph < Apia::Polymorph + + option "MonthLong", type: CoreAPI::Objects::MonthLong, matcher: proc { |time| time.sec.even? } + option "MonthShort", type: CoreAPI::Objects::MonthShort, matcher: proc { |time| time.sec.odd? } + + end + end +end diff --git a/examples/core_api/objects/month_short.rb b/examples/core_api/objects/month_short.rb new file mode 100644 index 0000000..af4dfd9 --- /dev/null +++ b/examples/core_api/objects/month_short.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module CoreAPI + module Objects + class MonthShort < Apia::Object + + description "Represents a month" + + field :month_short, type: :string do + backend { |t| t.strftime("%b") } + end + + end + end +end diff --git a/examples/core_api/objects/time.rb b/examples/core_api/objects/time.rb new file mode 100644 index 0000000..3550841 --- /dev/null +++ b/examples/core_api/objects/time.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require "core_api/objects/day" +require "core_api/objects/year" +require "core_api/objects/month_polymorph" + +module CoreAPI + module Objects + class Time < Apia::Object + + description "Represents a time" + + field :unix, type: :unix_time do + backend { |t| t } + end + + field :day_of_week, type: Objects::Day do + backend { |t| t.strftime("%A") } + end + + field :full, type: :string do + backend { |t| t.to_s } + end + + field :year, type: Objects::Year do + backend { |t| t.year } + end + + field :month, type: Objects::MonthPolymorph do + backend { |t| t } + end + + field :as_array, type: [:integer] do + backend { |t| [t.year, t.month, t.day, t.hour, t.min, t.sec] } + end + + field :as_array_of_objects, type: [Objects::Year] do + backend { |t| [t.year] } + end + + field :as_decimal, type: :decimal do + backend { |t| t.to_f } + end + + field :as_base64, type: :base64 do + backend { |t| Base64.encode64(t.to_s) } + end + + end + end +end diff --git a/examples/core_api/objects/time_zone.rb b/examples/core_api/objects/time_zone.rb new file mode 100644 index 0000000..fbba342 --- /dev/null +++ b/examples/core_api/objects/time_zone.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module CoreAPI + module Objects + class TimeZone < Apia::Enum + + value "Europe/London" + value "Europe/Madrid" + value "Asia/Singapore" + + end + end +end diff --git a/examples/core_api/objects/year.rb b/examples/core_api/objects/year.rb new file mode 100644 index 0000000..ffe109c --- /dev/null +++ b/examples/core_api/objects/year.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +require "core_api/objects/day" + +module CoreAPI + module Objects + class Year < Apia::Object + + description "Represents a year" + + field :as_integer, type: :integer do + backend(&:to_i) + end + + field :as_string, type: :string do + backend(&:to_s) + end + + end + end +end diff --git a/lib/apia/open_api.rb b/lib/apia/open_api.rb new file mode 100644 index 0000000..a3b9560 --- /dev/null +++ b/lib/apia/open_api.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +require_relative "open_api/version" +require_relative "open_api/rack" +require_relative "open_api/specification" diff --git a/lib/apia/open_api/helpers.rb b/lib/apia/open_api/helpers.rb new file mode 100644 index 0000000..9d1332a --- /dev/null +++ b/lib/apia/open_api/helpers.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +# A collection of 'utility' methods used across the various OpenAPI::Objects +module Apia + module OpenApi + module Helpers + + # A component schema is a re-usable schema that can be referenced by other parts of the spec + # e.g. { "$ref": "#/components/schemas/PaginationObject" } + def add_to_components_schemas(definition) + id = generate_id_from_definition(definition.type.klass.definition) + return unless @spec.dig(:components, :schemas, id).nil? + + component_schema = {} + @spec[:components][:schemas][id] = component_schema + Objects::Schema.new(spec: @spec, definition: definition, schema: component_schema).add_to_spec + end + + # TODO: prob turn into case statement and explicitly declare all types, raise on unknown type + def convert_type_to_open_api_data_type(type) + if type.klass == Apia::Scalars::UnixTime + "integer" + elsif type.klass == Apia::Scalars::Decimal + "number" + elsif type.klass == Apia::Scalars::Base64 + "string" + else + type.klass.definition.name.downcase + end + end + + def generate_schema_ref(definition) + id = generate_id_from_definition(definition) + { "$ref": "#/components/schemas/#{id}" } + end + + # forward slashes do not work in ids (e.g. schema ids) + def generate_id_from_definition(definition) + definition.id.gsub(/\//, "_") + end + + end + end +end diff --git a/lib/apia/open_api/objects.rb b/lib/apia/open_api/objects.rb new file mode 100644 index 0000000..c611bd2 --- /dev/null +++ b/lib/apia/open_api/objects.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +Dir.glob(File.join(File.dirname(__FILE__), "objects", "*.rb")).each do |file| + require_relative file +end + +module Apia + module OpenApi + module Objects + end + end +end diff --git a/lib/apia/open_api/objects/bearer_security_scheme.rb b/lib/apia/open_api/objects/bearer_security_scheme.rb new file mode 100644 index 0000000..ca44323 --- /dev/null +++ b/lib/apia/open_api/objects/bearer_security_scheme.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +# The BearerSecurityScheme object defines the required spec for authentication via a bearer token. +# +# "components": { +# "securitySchemes": { +# "CoreAPI_Authenticator": { +# "scheme": "bearer", +# "type": "http" +# } +# } +# }, +# "security": [ +# { +# "CoreAPI_Authenticator": [] +# } +# ] + +module Apia + module OpenApi + module Objects + class BearerSecurityScheme + + include Apia::OpenApi::Helpers + + def initialize(spec:, authenticator:) + @spec = spec + @authenticator = authenticator + end + + def add_to_spec + @spec[:components][:securitySchemes] ||= {} + @spec[:components][:securitySchemes][generate_id_from_definition(@authenticator.definition)] = { + scheme: "bearer", + type: "http" + } + + @spec[:security] << { + generate_id_from_definition(@authenticator.definition) => [] + } + end + + end + end + end +end diff --git a/lib/apia/open_api/objects/parameters.rb b/lib/apia/open_api/objects/parameters.rb new file mode 100644 index 0000000..4e5394f --- /dev/null +++ b/lib/apia/open_api/objects/parameters.rb @@ -0,0 +1,94 @@ +# frozen_string_literal: true + +# Parameters describe the arguments that can be passed to an endpoint via the query string. +# We only declare these for GET requests, otherwise we define a request body. +# +# "parameters": [ +# { +# "name": "data_center[id]", +# "in": "query", +# "schema": { +# "type": "string" +# } +# }, +# { +# "name": "data_center[permalink]", +# "in": "query", +# "schema": { +# "type": "string" +# } +# } +# ] +module Apia + module OpenApi + module Objects + class Parameters + + include Apia::OpenApi::Helpers + + def initialize(spec:, argument:, route_spec:) + @spec = spec + @argument = argument + @route_spec = route_spec + end + + def add_to_spec + if @argument.type.argument_set? + # complex argument sets are not supported in query params (e.g. nested objects) + @argument.type.klass.definition.arguments.each_value do |child_arg| + param = { + name: "#{@argument.name}[#{child_arg.name}]", + in: "query", + schema: { + type: convert_type_to_open_api_data_type(child_arg.type) + } + } + add_to_parameters(param) + end + elsif @argument.array? + if @argument.type.enum? || @argument.type.object? # polymorph? + items = generate_schema_ref(@argument.type.klass.definition) + add_to_components_schemas(@argument) + else + items = { type: convert_type_to_open_api_data_type(@argument.type) } + end + + param = { + name: "#{@argument.name}[]", + in: "query", + schema: { + type: "array", + items: items + } + } + add_to_parameters(param) + elsif @argument.type.enum? + param = { + name: @argument.name.to_s, + in: "query", + schema: generate_schema_ref(@argument.type.klass.definition) + } + add_to_parameters(param) + add_to_components_schemas(@argument) + else + param = { + name: @argument.name.to_s, + in: "query", + schema: { + type: convert_type_to_open_api_data_type(@argument.type) + } + } + add_to_parameters(param) + end + end + + private + + def add_to_parameters(param) + @route_spec[:parameters] << param + end + + end + end + end +end diff --git a/lib/apia/open_api/objects/path.rb b/lib/apia/open_api/objects/path.rb new file mode 100644 index 0000000..1f46bca --- /dev/null +++ b/lib/apia/open_api/objects/path.rb @@ -0,0 +1,109 @@ +# frozen_string_literal: true + +# A Path Object describes a single endpoint in the API +# +# "paths": { +# "/data_centers/:data_center": { +# "get": { +# "operationId": "get:data_center", +# "tags": ["Core"], +# "parameters": [...], +# "responses": {...}, +# } +# }, +# "/virtual_machines/:virtual_machine/start": { +# "post": { +# "operationId": "post:virtual_machine_start", +# "requestBody": {...} +# "responses": { +# "200": {...} +# } +# } +# } +# } + +module Apia + module OpenApi + module Objects + class Path + + include Apia::OpenApi::Helpers + + def initialize(spec:, path_ids:, route:, name:) + @spec = spec + @path_ids = path_ids + @route = route + @route_spec = { + operationId: convert_route_to_id, + tags: [name] + } + end + + def add_to_spec + path = @route.path + if @route.request_method == :get + add_parameters + else + add_request_body + end + + @spec[:paths]["/#{path}"] ||= {} + @spec[:paths]["/#{path}"][@route.request_method.to_s] = @route_spec + + add_responses + end + + private + + # aka query params + def add_parameters + @route_spec[:parameters] ||= [] + + @route.endpoint.definition.argument_set.definition.arguments.each_value do |arg| + Parameters.new(spec: @spec, argument: arg, route_spec: @route_spec).add_to_spec + end + end + + def add_request_body + RequestBody.new(spec: @spec, route: @route, route_spec: @route_spec).add_to_spec + end + + def add_responses + Response.new(spec: @spec, path_ids: @path_ids, route: @route, route_spec: @route_spec).add_to_spec + end + + # It's worth creating a 'nice' operationId for each route, as this is used as the + # basis for the method name when calling the endpoint using a generated client. + def convert_route_to_id + parts = @route.path.split("/") + params = parts.each_with_object([]) do |part, memo| + memo << part[1..] if part.start_with?(":") + end + result_parts = [] + + parts.each do |part| + if part.start_with?(":") + part_without_prefix = part[1..] + next if result_parts.include?(part_without_prefix) + + result_parts << part_without_prefix + elsif params.none? { |param| part == param || part.match(/#{param.pluralize}/) } + result_parts << part + end + end + + id = "#{@route.request_method}:#{result_parts.join('_')}" + if @path_ids.include?(id) + # TODO: make sure example app triggers this + # an existing route has already produced the same id, fallback to the full path + id = "#{@route.request_method}:#{@route.path}" + end + @path_ids << id + + id + end + + end + end + end +end diff --git a/lib/apia/open_api/objects/request_body.rb b/lib/apia/open_api/objects/request_body.rb new file mode 100644 index 0000000..d547827 --- /dev/null +++ b/lib/apia/open_api/objects/request_body.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +# A RequestBody Object describes the payload body that can be passed to an endpoint +# These are declared (if necessary) for any endpoint that is not a GET request. +# +# "requestBody": { +# "content": { +# "application/json": { +# "schema": { +# "properties": { +# "virtual_machine": { +# "$ref": "#/components/schemas/CoreAPI_ArgumentSets_VirtualMachineLookup" +# } +# } +# } +# } +# } +# } +module Apia + module OpenApi + module Objects + class RequestBody + + include Apia::OpenApi::Helpers + + def initialize(spec:, route:, route_spec:) + @spec = spec + @route = route + @route_spec = route_spec + @properties = {} + end + + def add_to_spec + @route.endpoint.definition.argument_set.definition.arguments.each_value do |arg| + if arg.array? + if arg.type.argument_set? || arg.type.enum? + items = generate_schema_ref(arg.type.klass.definition) + add_to_components_schemas(arg) + else + items = { type: convert_type_to_open_api_data_type(arg.type) } + end + + @properties[arg.name.to_s] = { + type: "array", + items: items + } + elsif arg.type.argument_set? || arg.type.enum? + @properties[arg.name.to_s] = generate_schema_ref(arg.type.klass.definition) + add_to_components_schemas(arg) + else # scalar + @properties[arg.name.to_s] = { + type: convert_type_to_open_api_data_type(arg.type) + } + end + end + + # TODO: description + # TODO: required + @route_spec[:requestBody] = { + content: { + "application/json": { + schema: { + properties: @properties + } + } + } + } + end + + end + end + end +end diff --git a/lib/apia/open_api/objects/response.rb b/lib/apia/open_api/objects/response.rb new file mode 100644 index 0000000..f38a205 --- /dev/null +++ b/lib/apia/open_api/objects/response.rb @@ -0,0 +1,152 @@ +# frozen_string_literal: true + +# For each endpoint, we need to generate a response schema. +# +# "responses": { +# "200": { +# "description": "Format the given time", +# "content": { +# "application/json": { +# "schema": { +# "properties": { +# "formatted_time": { +# "type": "string" +# } +# }, +# "required": [ +# "formatted_time" +# ] +# } +# } +# } +# } +# } +module Apia + module OpenApi + module Objects + class Response + + include Apia::OpenApi::Helpers + + def initialize(spec:, path_ids:, route:, route_spec:) + @spec = spec + @path_ids = path_ids + @route = route + @endpoint = route.endpoint + @route_spec = route_spec + end + + def add_to_spec + response_schema = { + properties: generate_properties_for_response + } + + required_fields = @endpoint.definition.fields.select { |_, field| field.condition.nil? } + response_schema[:required] = required_fields.keys if required_fields.any? + + @route_spec[:responses] = { + "#{@endpoint.definition.http_status}": { + description: @endpoint.definition.description || "", + content: { + "application/json": { + schema: response_schema + } + } + } + } + end + + private + + def generate_properties_for_response + @endpoint.definition.fields.reduce({}) do |props, (name, field)| + props.merge(generate_properties_for_field(name, field)) + end + end + + # Response fields can often just point to a ref of a schema. But it's also possible to reference + # a return type and not include all fields of that type. If `field.include` is defined, we need + # to inspect it to determine which fields are included. + def generate_properties_for_field(field_name, field) + properties = {} + if field.type.polymorph? + build_properties_for_polymorph(field_name, field, properties) + elsif field.array? + build_properties_for_array(field_name, field, properties) + elsif field.type.object? || field.type.enum? + build_properties_for_object_or_enum(field_name, field, properties) + else # scalar + properties[field_name] = { + type: convert_type_to_open_api_data_type(field.type) + } + end + properties + end + + def build_properties_for_polymorph(field_name, field, properties) + if field.include.nil? + refs = [] + field.type.klass.definition.options.map do |_, polymorph_option| + refs << generate_schema_ref(polymorph_option.type.klass.definition) + add_to_components_schemas(polymorph_option) + end + properties[field_name] = { oneOf: refs } + else + # TODO + end + end + + def build_properties_for_array(field_name, field, properties) + if field.type.object? || field.type.enum? # polymorph? + if field_includes_all_properties?(field) + items = generate_schema_ref(field.type.klass.definition) + add_to_components_schemas(field) + else + array_schema = {} + Objects::Schema.new( + spec: @spec, + definition: field, + schema: array_schema, + endpoint: @endpoint, + path: [field] + ).add_to_spec + if array_schema[:properties].any? + items = array_schema + end + end + else + items = { type: convert_type_to_open_api_data_type(field.type) } + end + return unless items + + properties[field_name] = { + type: "array", + items: items + } + end + + def build_properties_for_object_or_enum(field_name, field, properties) + if field_includes_all_properties?(field) + properties[field_name] = generate_schema_ref(field.type.klass.definition) + add_to_components_schemas(field) + else + object_schema = {} + Objects::Schema.new( + spec: @spec, + definition: field, + schema: object_schema, + endpoint: @endpoint, + path: [field] + ).add_to_spec + properties[field_name] = object_schema + end + end + + def field_includes_all_properties?(field) + field.include.nil? + end + + end + end + end +end diff --git a/lib/apia/open_api/objects/schema.rb b/lib/apia/open_api/objects/schema.rb new file mode 100644 index 0000000..20623bf --- /dev/null +++ b/lib/apia/open_api/objects/schema.rb @@ -0,0 +1,156 @@ +# frozen_string_literal: true + +# Schema Objects loosley map to the re-usable parts of an Apia API, such as: +# ArgumentSet, Object, Enum, Polymorph +# +# "PaginationObject": { +# "type": "object", +# "properties": { +# "current_page": { +# "type": "integer" +# }, +# "total_pages": { +# "type": "integer" +# }, +# "total": { +# "type": "integer" +# }, +# "per_page": { +# "type": "integer" +# }, +# } +# } +# +# We generate Schema Objects for two reasons: +# 1. They are added to the components section of the spec, so they can be referenced and re-used from elsewhere. +# e.g. the pagination object example above would be referenced from endpoint responses as: +# { "$ref": "#/components/schemas/PaginationObject" } +# +# 2. When the response does not include all fields from an existing Objects::Schema, we cannot use a $ref. +# So we generate a new Objects::Schema and include it 'inline' for that specific endpoint. +module Apia + module OpenApi + module Objects + class Schema + + include Apia::OpenApi::Helpers + + def initialize(spec:, definition:, schema:, endpoint: nil, path: nil) + @spec = spec + @definition = definition + @schema = schema + @endpoint = endpoint + @path = path + @children = [] + end + + def add_to_spec + if @definition.type.polymorph? + build_schema_for_polymorph + return @schema + elsif @definition.respond_to?(:array?) && @definition.array? + build_schema_for_array + end + + generate_child_schemas + + @schema + end + + private + + def build_schema_for_polymorph + @schema[:type] = "object" + @schema[:properties] ||= {} + refs = [] + @definition.type.klass.definition.options.map do |_, polymorph_option| + refs << generate_schema_ref(polymorph_option.type.klass.definition) + add_to_components_schemas(polymorph_option) + end + @schema[:properties][@definition.name.to_s] = { oneOf: refs } + end + + def build_schema_for_array + @schema[:type] = "object" + @schema[:properties] ||= {} + if @definition.type.argument_set? || @definition.type.enum? || @definition.type.object? + if @definition.type.argument_set? + # TODO: add array of argument sets to the example app (refer to CoreAPI::ArgumentSets::KeyValue) + @children = @definition.type.klass.definition.arguments.values + else + @children = @definition.type.klass.definition.fields.values + end + else + items = { type: convert_type_to_open_api_data_type(@definition.type) } + end + + return unless items + + # TODO: ensure this is triggered by example API + + @schema[:properties][@definition.name.to_s] = { + type: "array", + items: items + } + @schema + end + + def generate_child_schemas + if @definition.type.argument_set? + @children = @definition.type.klass.definition.arguments.values + elsif @definition.type.object? + @children = @definition.type.klass.definition.fields.values + elsif @definition.type.enum? + @children = @definition.type.klass.definition.values.values + end + + return if @children.empty? + + all_properties_included = @definition.type.enum? || @endpoint.nil? + @children.each do |child| + next unless @endpoint.nil? || (!@definition.type.enum? && @endpoint.include_field?(@path + [child.name])) + + generate_schema_for_child(child, all_properties_included) + end + end + + def generate_schema_for_child(child, all_properties_included) + if @definition.type.enum? + @schema[:type] = "string" + @schema[:enum] = @children.map { |c| c[:name] } + elsif child.type.argument_set? || child.type.enum? || child.type.polymorph? + @schema[:type] = "object" + @schema[:properties] ||= {} + @schema[:properties][child.name.to_s] = generate_schema_ref(child.type.klass.definition) + add_to_components_schemas(child) + elsif child.type.object? + @schema[:type] = "object" + @schema[:properties] ||= {} + if all_properties_included + @schema[:properties][child.name.to_s] = generate_schema_ref(child.type.klass.definition) + add_to_components_schemas(child) + else + child_path = @path.nil? ? nil : @path + [child] + child_schema = {} + @schema[:properties][child.name.to_s] = child_schema + self.class.new( + spec: @spec, + definition: child, + schema: child_schema, + endpoint: @endpoint, + path: child_path + ).add_to_spec + end + else # scalar + @schema[:type] = "object" + @schema[:properties] ||= {} + @schema[:properties][child.name.to_s] = { + type: convert_type_to_open_api_data_type(child.type) + } + end + end + + end + end + end +end diff --git a/lib/apia/open_api/rack.rb b/lib/apia/open_api/rack.rb new file mode 100644 index 0000000..d3d1621 --- /dev/null +++ b/lib/apia/open_api/rack.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +module Apia + module OpenApi + class Rack + + def initialize(app, api_class:, schema_path:, **options) + @app = app + @api_class = api_class + @schema_path = "/#{schema_path.sub(/\A\/+/, '').sub(/\/+\z/, '')}" + @options = options + end + + def development? + env_is_dev = ENV["RACK_ENV"] == "development" + return true if env_is_dev && @options[:development].nil? + + @options[:development] == true + end + + def api_class + return Object.const_get(@api_class) if @api_class.is_a?(String) && development? + return @cached_api ||= Object.const_get(@api_class) if @api_class.is_a?(String) + + @api_class + end + + def base_url + @options[:base_url] || "https://api.example.com/api/v1" + end + + def call(env) + if @options[:hosts]&.none? { |host| host == env["HTTP_HOST"] } + return @app.call(env) + end + + unless env["PATH_INFO"] == @schema_path + return @app.call(env) + end + + specification = Specification.new(api_class, base_url, @options[:name]) + body = specification.json + + [200, { "Content-Type" => "application/json", "Content-Length" => body.bytesize.to_s }, [body]] + end + + end + end +end diff --git a/lib/apia/open_api/specification.rb b/lib/apia/open_api/specification.rb new file mode 100644 index 0000000..7bda212 --- /dev/null +++ b/lib/apia/open_api/specification.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +require "active_support/inflector" +require_relative "helpers" +require_relative "objects" + +module Apia + module OpenApi + class Specification + + include Apia::OpenApi::Helpers + + OPEN_API_VERSION = "3.0.0" # The Ruby client generator currently only supports v3.0.0 https://openapi-generator.tech/ + + def initialize(api, base_url, name) + @api = api + @base_url = base_url + @name = name || "Core" # will be suffixed with 'Api' and used in the client generator + @spec = { + openapi: OPEN_API_VERSION, + info: {}, + servers: [], + paths: {}, + components: { + schemas: {} + }, + security: [] + } + @path_ids = [] + build_spec + end + + def json + JSON.pretty_generate(@spec) + end + + private + + def build_spec + add_info + add_servers + add_paths + add_security + end + + def add_info + @spec[:info] = { + version: "1.0.0", # TODO: can we actually read the api version? + title: @api.definition.name || @api.definition.id + } + @spec[:info][:description] = @api.definition.description unless @api.definition.description.nil? + end + + def add_servers + @spec[:servers] << { url: @base_url } + end + + def add_paths + @api.definition.route_set.routes.each do |route| + next unless route.endpoint.definition.schema? # not all routes should be documented + + Objects::Path.new(spec: @spec, path_ids: @path_ids, route: route, name: @name).add_to_spec + end + end + + def add_security + @api.objects.select { |o| o.ancestors.include?(Apia::Authenticator) }.each do |authenticator| + next unless authenticator.definition.type == :bearer + + Objects::BearerSecurityScheme.new(spec: @spec, authenticator: authenticator).add_to_spec + end + end + + end + end +end diff --git a/lib/apia/open_api/version.rb b/lib/apia/open_api/version.rb new file mode 100644 index 0000000..8e642f2 --- /dev/null +++ b/lib/apia/open_api/version.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Apia + module OpenApi + + VERSION = "0.1.0" + + end +end diff --git a/spec/apia/open_api/specification_spec.rb b/spec/apia/open_api/specification_spec.rb new file mode 100644 index 0000000..b9b3b34 --- /dev/null +++ b/spec/apia/open_api/specification_spec.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +require "spec_helper" +require "core_api/base" + +RSpec.describe Apia::OpenApi::Specification do + describe "#json" do + it "produces OpenAPI JSON" do + base_url = "http://127.0.0.1:9292/core/v1/" + example_api = CoreAPI::Base + + spec = described_class.new(example_api, base_url, "Core") + + expected_spec = File.read("spec/support/fixtures/openapi.json") + + expect(spec.json).to eq(expected_spec) + end + end +end diff --git a/spec/apia/open_api_spec.rb b/spec/apia/open_api_spec.rb new file mode 100644 index 0000000..4cca5e3 --- /dev/null +++ b/spec/apia/open_api_spec.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +RSpec.describe Apia::OpenApi do + it "has a version number" do + expect(Apia::OpenApi::VERSION).not_to be nil + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..4b9bc6a --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +SPEC_ROOT = __dir__ +$LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) +$LOAD_PATH.unshift(File.expand_path("../examples", __dir__)) + +require "apia" +require "apia/open_api" + +RSpec.configure do |config| + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = ".rspec_status" + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end +end diff --git a/spec/support/fixtures/openapi.json b/spec/support/fixtures/openapi.json new file mode 100644 index 0000000..c0bb816 --- /dev/null +++ b/spec/support/fixtures/openapi.json @@ -0,0 +1,678 @@ +{ + "openapi": "3.0.0", + "info": { + "version": "1.0.0", + "title": "CoreAPI/Base" + }, + "servers": [ + { + "url": "http://127.0.0.1:9292/core/v1/" + } + ], + "paths": { + "/example/format": { + "get": { + "operationId": "get:example_format", + "tags": [ + "Core" + ], + "parameters": [ + { + "name": "time[unix]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "time[string]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "timezone", + "in": "query", + "schema": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + } + ], + "responses": { + "200": { + "description": "Format the given time", + "content": { + "application/json": { + "schema": { + "properties": { + "formatted_time": { + "type": "string" + } + }, + "required": [ + "formatted_time" + ] + } + } + } + } + } + }, + "post": { + "operationId": "post:example_format", + "tags": [ + "Core" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "$ref": "#/components/schemas/CoreAPI_ArgumentSets_TimeLookupArgumentSet" + }, + "timezone": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Format the given time", + "content": { + "application/json": { + "schema": { + "properties": { + "formatted_time": { + "type": "string" + } + }, + "required": [ + "formatted_time" + ] + } + } + } + } + } + } + }, + "/example/format_multiple": { + "post": { + "operationId": "post:example_format_multiple", + "tags": [ + "Core" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "times": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CoreAPI_ArgumentSets_TimeLookupArgumentSet" + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Format the given times", + "content": { + "application/json": { + "schema": { + "properties": { + "formatted_times": { + "type": "array", + "items": { + "type": "string" + } + }, + "times": { + "type": "array", + "items": { + "type": "object", + "properties": { + "unix": { + "type": "integer" + }, + "year": { + "type": "object", + "properties": { + "as_string": { + "type": "string" + } + } + }, + "as_array_of_objects": { + "type": "object", + "properties": { + "as_integer": { + "type": "integer" + } + } + } + } + } + } + }, + "required": [ + "formatted_times", + "times" + ] + } + } + } + } + } + } + }, + "/time/now": { + "get": { + "operationId": "get:time_now", + "tags": [ + "Core" + ], + "parameters": [ + { + "name": "timezone", + "in": "query", + "schema": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + }, + { + "name": "time_zones[]", + "in": "query", + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + } + }, + { + "name": "filters[]", + "in": "query", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + ], + "responses": { + "200": { + "description": "Returns the current time", + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "$ref": "#/components/schemas/CoreAPI_Objects_Time" + }, + "time_zones": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + }, + "filters": { + "type": "array", + "items": { + "type": "string" + } + }, + "my_polymorph": { + "oneOf": [ + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthLong" + }, + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthShort" + } + ] + } + }, + "required": [ + "time", + "time_zones", + "filters", + "my_polymorph" + ] + } + } + } + } + } + }, + "post": { + "operationId": "post:time_now", + "tags": [ + "Core" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "timezone": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + }, + "time_zones": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + }, + "filters": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Returns the current time", + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "$ref": "#/components/schemas/CoreAPI_Objects_Time" + }, + "time_zones": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + }, + "filters": { + "type": "array", + "items": { + "type": "string" + } + }, + "my_polymorph": { + "oneOf": [ + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthLong" + }, + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthShort" + } + ] + } + }, + "required": [ + "time", + "time_zones", + "filters", + "my_polymorph" + ] + } + } + } + } + } + } + }, + "/test/:object": { + "get": { + "operationId": "get:test_object", + "tags": [ + "Core" + ], + "parameters": [ + { + "name": "object[id]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "object[permalink]", + "in": "query", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Returns the current time", + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "type": "object", + "properties": { + "unix": { + "type": "integer" + }, + "day_of_week": { + "$ref": "#/components/schemas/CoreAPI_Objects_Day" + }, + "year": { + "type": "object", + "properties": { + "as_string": { + "type": "string" + } + } + } + } + }, + "object_id": { + "type": "string" + } + }, + "required": [ + "object_id" + ] + } + } + } + } + } + }, + "post": { + "operationId": "post:test_object", + "tags": [ + "Core" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "object": { + "$ref": "#/components/schemas/CoreAPI_ArgumentSets_ObjectLookup" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Returns the current time", + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "type": "object", + "properties": { + "unix": { + "type": "integer" + }, + "day_of_week": { + "$ref": "#/components/schemas/CoreAPI_Objects_Day" + }, + "year": { + "type": "object", + "properties": { + "as_string": { + "type": "string" + } + } + } + } + }, + "object_id": { + "type": "string" + } + }, + "required": [ + "object_id" + ] + } + } + } + } + } + } + }, + "/time/formatting/format": { + "get": { + "operationId": "get:time_formatting_format", + "tags": [ + "Core" + ], + "parameters": [ + { + "name": "time[unix]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "time[string]", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "timezone", + "in": "query", + "schema": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + } + ], + "responses": { + "200": { + "description": "Format the given time", + "content": { + "application/json": { + "schema": { + "properties": { + "formatted_time": { + "type": "string" + } + }, + "required": [ + "formatted_time" + ] + } + } + } + } + } + }, + "post": { + "operationId": "post:time_formatting_format", + "tags": [ + "Core" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "properties": { + "time": { + "$ref": "#/components/schemas/CoreAPI_ArgumentSets_TimeLookupArgumentSet" + }, + "timezone": { + "$ref": "#/components/schemas/CoreAPI_Objects_TimeZone" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Format the given time", + "content": { + "application/json": { + "schema": { + "properties": { + "formatted_time": { + "type": "string" + } + }, + "required": [ + "formatted_time" + ] + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "CoreAPI_Objects_TimeZone": { + "type": "string", + "enum": [ + "Europe/London", + "Europe/Madrid", + "Asia/Singapore" + ] + }, + "CoreAPI_ArgumentSets_TimeLookupArgumentSet": { + "type": "object", + "properties": { + "unix": { + "type": "string" + }, + "string": { + "type": "string" + } + } + }, + "CoreAPI_Objects_Time": { + "type": "object", + "properties": { + "unix": { + "type": "integer" + }, + "day_of_week": { + "$ref": "#/components/schemas/CoreAPI_Objects_Day" + }, + "full": { + "type": "string" + }, + "year": { + "$ref": "#/components/schemas/CoreAPI_Objects_Year" + }, + "month": { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthPolymorph" + }, + "as_array": { + "type": "integer" + }, + "as_array_of_objects": { + "$ref": "#/components/schemas/CoreAPI_Objects_Year" + }, + "as_decimal": { + "type": "number" + }, + "as_base64": { + "type": "string" + } + } + }, + "CoreAPI_Objects_Day": { + "type": "string", + "enum": [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ] + }, + "CoreAPI_Objects_Year": { + "type": "object", + "properties": { + "as_integer": { + "type": "integer" + }, + "as_string": { + "type": "string" + } + } + }, + "CoreAPI_Objects_MonthPolymorph": { + "type": "object", + "properties": { + "month": { + "oneOf": [ + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthLong" + }, + { + "$ref": "#/components/schemas/CoreAPI_Objects_MonthShort" + } + ] + } + } + }, + "CoreAPI_Objects_MonthLong": { + "type": "object", + "properties": { + "month_long": { + "type": "string" + } + } + }, + "CoreAPI_Objects_MonthShort": { + "type": "object", + "properties": { + "month_short": { + "type": "string" + } + } + }, + "CoreAPI_ArgumentSets_ObjectLookup": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "permalink": { + "type": "string" + } + } + } + }, + "securitySchemes": { + "CoreAPI_MainAuthenticator": { + "scheme": "bearer", + "type": "http" + } + } + }, + "security": [ + { + "CoreAPI_MainAuthenticator": [ + + ] + } + ] +} \ No newline at end of file