This project is the same as the project pushed on this repository we only changed the database from sqlite3 to MySQL and we added swagger to grape in order to generate documentation for our API music_stores_api previously created.
-
We worked with MySQL version 5.6.37.
-
Gems added to the project:
- mysql2 version 0.3.13 instead of sqlite3, mysql2 is a library which functions as MySQL adapter allowing us to connect and query MySQL database.
- grape-entity: allows to specify the attributes of our model exposed by the API.
- grape-swagger: allows to generate the documentation of our API from our code.
- grape-swagger-rails: allows to embark in our project Rails the UI of Swagger.
- Setting connection to MySQL database
- Add the mysql2 dependency to the gem file
gem 'mysql2', '~> 0.3.13'
- Configure the database connection in the config/database.yml file
adapter: mysql2
encoding: utf8
database: musicstores
username: root
password:
host: 127.0.0.1
port: 3306
development:
<<: *default
database: musicstores
- Run
$ rake db:migrate
so that our tables will be created as shown by Sequel Pro.
- Now we can test our api already connected to our MySQL database named musicstores but before that we will add swagger, a framework that provides capabilities to easily inspect API request-responses to crud functionalities, and make sure they work as expected.
- Adding swagger
- Add this dependencies to the gem file
gem 'grape-entity'
gem 'grape-swagger'
gem 'grape-swagger-rails'
- We need to configure grape-swagger-rails gem, so we create an initializer config/initializers/swagger.rb
GrapeSwaggerRails.options.url = '/api/swagger_doc'
GrapeSwaggerRails.options.app_name = 'music_stores_api'
GrapeSwaggerRails.options.app_url = 'http://localhost:3000'
- To display the swagger UI we need to specify his route in config/routes.rb
mount GrapeSwaggerRails::Engine => ‘/apidoc'
- In order to generate swagger documentation for our api we need to configure grape_swagger gem in our root node api/api.rb where our api is mounted. So we add add_swagger_documentation function as shown
add_swagger_documentation(
api_version: "v1",
hide_documentation_path: true,
mount_path: "/api/v1/swagger_doc",
hide_format: true
)
NB: we have to run bundle install after adding gems in our gem file.
- Then our API is ready for test with swagger.
- Verify database
- View modification
- View modification