OpenApiAnnotator realizes to generate OpenAPI spec by annotating to controllers and serializers. If you use ActiveModelSerializer, this is the best way to generate OpenAPI spec.
Add this line to your application's Gemfile:
gem'open_api_annotator'Annotating controllers and serializers, you can generate OpenAPI spec file from these. Things you have to do are three below:
- Configure API meta information
- Annotate controllers
- Annotate serializers
You have to set API meta information like:
# config/initializers/open_api_annotator.rbOpenApiAnnotator.configuredo |config|
config.info=OpenApi::Info.new(title: "Book API",version: "1")config.destination_path=Rails.root.join("api_spec.yml")config.path_regexp=/\Aapi\/v1\//# If you want to restrict a path to createendTo define an entity of an endpoint, call the method endpoint in the previous line of an action method. It takes entity expression as the first arg. Entity expression is a model class or an array that contains only one model class.
classApi::V1::BooksControllerendpoint[Book]# 👈It means an array of Bookdefindexbooks=Book.limit(10)renderjson: booksendendpointBook# 👈Just a Bookdefshowbook=Book.find(params[:id])renderjson: bookendendpointBook# 👈Just a Bookdefupdatebook=Book.find(params[:id])book.update!(book_params)renderjson: bookendendTo define an schema in components, set type, format, nullable as each field option.
classBookSerializer < ApplicationSerializerattribute:title,type: :string,nullable: falseattribute:published_at,type: :string,format: :"date-time",nullable: truehas_many:authors,type: [Author],nullable: falsehas_one:cover_image,type: CoverImage,nullable: truebelongs_to:publisher,type: Publisher,nullable: falseendAfter checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number using bundle exec bump patch(or minor, major), and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.
Bug reports and pull requests are welcome on GitHub at https://github.com/wantedly/open_api_annotator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the OpenApiAnnotator project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.