Code Monkey home page Code Monkey logo

grape-swagger-rails's Introduction

GrapeSwaggerRails

Gem Version Tests Code Climate

Swagger UI as Rails Engine for grape-swagger gem.

Table of Contents

Installation

Add this line to your application's Gemfile:

gem 'grape-swagger-rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install grape-swagger-rails

Compatibility

GrapeSwaggerRails is compatible with the following versions of grape and grape-swagger.

grape grape-swagger
0.9.0 0.8.0
0.10.0 0.9.0
0.16.2 0.20.2

Usage

Add this line to ./config/routes.rb:

mount GrapeSwaggerRails::Engine => '/swagger'

Create an initializer (e.g. ./config/initializers/swagger.rb) and specify the URL to your Swagger API schema and app:

GrapeSwaggerRails.options.url      = '/swagger_doc.json'
GrapeSwaggerRails.options.app_url  = 'http://swagger.wordnik.com'

You can dynamically set app_url for each request use a before_action:

GrapeSwaggerRails.options.before_action do
  GrapeSwaggerRails.options.app_url = request.protocol + request.host_with_port
end

You can set the app name, default is "Swagger".

GrapeSwaggerRails.options.app_name = 'Swagger'

You can specify additional headers to add to each request:

GrapeSwaggerRails.options.headers['Special-Header'] = 'Some Secret Value'

You can set docExpansion with "none" or "list" or "full", default is "none". See the official Swagger-UI documentation about SwaggerUi Parameters.

GrapeSwaggerRails.options.doc_expansion = 'list'

You can set supportedSubmitMethods with an array of the supported HTTP methods, default is %w{ get post put delete patch }.

See the official Swagger-UI documentation about SwaggerUi Parameters.

GrapeSwaggerRails.options.supported_submit_methods = ["get"]

You can set validatorUrl to your own locally deployed Swagger validator, or disable validation by setting this option to nil. This is useful to avoid error messages when running Swagger-UI on a server which is not accessible from outside your network.

GrapeSwaggerRails.options.validator_url = nil

Using the headers option above, you could hard-code Basic Authentication credentials. Alternatively, you can configure Basic Authentication through the UI, as described below.

Basic Authentication

If your application uses Basic Authentication, you can setup Swagger to send the username and password to the server with each request to your API:

GrapeSwaggerRails.options.api_auth     = 'basic' # Or 'bearer' for OAuth
GrapeSwaggerRails.options.api_key_name = 'Authorization'
GrapeSwaggerRails.options.api_key_type = 'header'

Now you can specify the username and password to your API in the Swagger "API key" field by concatenating the values like this:

username:password

The javascript that loads on the Swagger page automatically encodes the username and password and adds the authorization header to your API request. See the official Swagger documentation about Custom Header Parameters

Pre-fill Authentication

If you will know the Authentication key prior to page load or you wish to set it for debug purposes, you can setup so that the api_key field is pre-filled on page load:

GrapeSwaggerRails.options.api_key_default_value = 'your_default_value'

To set it based on the current_user or other request-based parameters, try using it inside of your before_action (See Swagger UI Authorization)

API Token Authentication

If your application uses token authentication passed as a query param, you can setup Swagger to send the API token along with each request to your API:

GrapeSwaggerRails.options.api_key_name = 'api_token'
GrapeSwaggerRails.options.api_key_type = 'query'

If your application used token authentication passed as a header, like Rails does (authenticate_or_request_with_http_token), you can configure Swagger to send the token in this form:

Authorization: Token token="WCZZYjnOQFUYfJIN2ShH1iD24UHo58A6TI"

by specify:

GrapeSwaggerRails.options.api_auth = 'token'
GrapeSwaggerRails.options.api_key_name = 'Authorization'
GrapeSwaggerRails.options.api_key_type = 'header'
GrapeSwaggerRails.options.api_key_placeholder = 'authorization_token'

You can use the authorization_token input box to fill in your API token.

Swagger UI Authorization

You may want to authenticate users before displaying the Swagger UI, particularly when the API is protected by Basic Authentication. Use the before option to inspect the request before Swagger UI:

GrapeSwaggerRails.options.before_action do |request|
  # 1. Inspect the `request` or access the Swagger UI controller via `self`.
  # 2. Check `current_user` or `can? :access, :api`, etc.
  # 3. Redirect or error in case of failure.
end

Integration with DoorKeeper

Add the following code to the initializer (swagger.rb):

GrapeSwaggerRails.options.before_action do |request|
  GrapeSwaggerRails.options.api_key_default_value = current_user.token.token
end

In your User model (user.rb) add:

has_one :token, -> { order 'created_at DESC' }, class_name: Doorkeeper::AccessToken, foreign_key: :resource_owner_id

Hiding the API or Authorization text boxes

If you know in advance that you would like to prevent changing the Swagger API URL, you can hide it using the following:

GrapeSwaggerRails.options.hide_url_input = true

Similarly, you can hide the Authentication input box by adding this:

GrapeSwaggerRails.options.hide_api_key_input = true

By default, these options are false.

Updating Swagger UI from Dist

To update Swagger UI from its distribution, run bundle exec rake swagger_ui:dist:update. Examine the changes carefully.

NOTE: This action should be run part of this gem (not your application). In case if you want to make it up-to-date, clone the repo, run the rake task, examine the diff, fix any bugs, make sure tests pass and then send PR here.

Enabling in a Rails-API Project

The grape-swagger-rails gem uses the Rails asset pipeline for its Javascript and CSS. Enable the asset pipeline with rails-api.

Add sprockets to config/application.rb.

require 'sprockets/railtie'

Include JavaScript in app/assets/javascripts/application.js.

//
//= require_tree .

Include CSS stylesheets in app/assets/stylesheets/application.css.

/*
*= require_tree .
*/

Enabling in Rails 6 (Sprokets 5)

Rails 6 top-level targets are determined via ./app/assets/config/manifest.js. Specify grape-swagger-rails asset files as follows.

//= link grape_swagger_rails/application.css
//= link grape_swagger_rails/application.js

See Upgrading Sprokets for more information.

Contributors

Contributing

See CONTRIBUTING.

License

MIT License, see LICENSE.

grape-swagger-rails's People

Contributors

aaronchi avatar anaumov avatar bitboxer avatar calfzhou avatar dapi avatar dblock avatar duffn avatar faisal-nfl avatar ghilead avatar jack12816 avatar jnill avatar joelvh avatar jrmhaig avatar maruware avatar mrclmrvn avatar nhinze avatar nitr avatar olleolleolle avatar onomated avatar pezholio avatar radanisk avatar rjocoleman avatar sedx avatar serggl avatar sofiasousa avatar swistaczek avatar tuliang avatar tyr0 avatar unloved avatar untidy-hair avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grape-swagger-rails's Issues

CSRF prevention tokens in cookies

Hi,
my grape APIs are protected against CSRF through a X-CSRF-Token request header. The value that has to go into this header is sent by the server to clients through a cookie.

Is there a way to customise grape-swagger-rails to add this header to every request?
Ex.

xhr.setRequestHeader('X-CSRF-Token', $.cookie('CSRF-Token'))

Exclude grape and grape-swagger from deps

Hello,
Please exclude grape and grape-swagger from gem dependencies. Main reason for this usage of grape-swagger-rails only as swagger-ui without code that depends on grape or/and grape-swagger.

Use "request" data for default app_url

Is it possible to use "request" data to generate a default app_url that is always relative to the host where it was accessed from?

While we don't use it in a multi tenancy application (which would be a valid use case for that), our current development environment have some host variations that cannot be easily (in a clear way) bypassed.

Support multiple "documentation pages"

Right now grape-swagger-rails expects to be mounted only once, at a single route. It also expects a single global definition of options.url, options.app_url, etc.

It would be really useful if we could mount multiple "swagger roots", just like we can mount multiple APIs at different routes using Grape itself. I think it'll also go a long way towards supporting issues like ruby-grape/grape-swagger#141 and at the very least provide a nice workaround

Would this be something you'd be open to supporting? I'm thinking it'll look something like you can specify a set of options per-mount and you can mount multiple subclasses of GrapeSwaggerRails::Engine at different routes.

P/S: The reason we need this now is due to Swagger 2.0's decision to only support one endpoint/operation for each (unique resource path + HTTP method) combo. The version of swagger-ui vendored here assumes this and only documents the last-mounted endpoint for each path. Since we use accept-header-only versioning, obviously this is very bad for us.

Add ability to namespace request URLs

Is there a way to namespace request routes generated by Grape::API endpoints?

I am using grape and grape-swagger-rails inside a rails engine and the URLs generated in the swagger UI don't include that namespace.

Ex.
My engine is called BlogManager an my routes file looks like this:

mount GrapeSwaggerRails::Engine, at: "/documentation"

The problem is that in the UI the generated URLs look like these:

  • /api/v1/tags (GET)
  • /api/v1/tags (POST)

which don't have the namespace /blog_manager and the try it out button obviously fail.

Help with configuration

Running into trouble with configuration for my rails app. I'm using the following versions

#Gemfile.lock
grape (0.14.0)
grape-swagger (0.10.4)
grape-swagger-rails (0.2.0)

I have the following initializer:

#config/initializer/swagger.rb
GrapeSwaggerRails.options.before_filter_proc = proc {
  GrapeSwaggerRails.options.app_url = request.protocol + request.host_with_port
}
GrapeSwaggerRails.options.url = '/api/v1/swagger_doc.json'

And I have the following API class:

#app/api/api.rb
require 'grape-swagger'

class API < Grape::API
  prefix 'api'
  version 'v1', using: :path

  mount People::List
  mount Person::Single

  add_swagger_documentation 
end

The following routes:

#config/routes.rb
mount API => '/'
mount GrapeSwaggerRails::Engine => '/api-docs'

When I visit /api-docs everything appears to start to load correctly but the AJAX calls being made by swagger-ui.js are hitting urls formatted like this: http://somedomain/api/v1/swagger_doc.json/people.json

I have no idea now what is causing /swagger_doc.json to be dropped inside of the request urls?

I feel like I am missing something fundamental but I haven't been able to figure it out. Any information that might be helpful would be appreciated.

Thanks

problems with request URL

Dear develeoper(s),

I have a server with multiple rails apps, each one deployed with a subURI scheme (like "www.lorem.ipsum/app_name/").
I configured your gem so the UI comes up with the following URL"http://www.lorem.ipsum/dbkzakat/takearest/apidoc" -> mount GrapeSwaggerRails::Engine, at: "/takearest/apidoc"

At the bottom of the screen a valid URL ist shown: [ base url: http://www.lorem.ipsum/dbkzakat/takearest/swagger_doc , api version: v1 ]
On top of the screen, also a valid URL shows up: http://www.lorem.ipsum/dbkzakat/takearest/swagger_doc

This works fine so far, now for the problem :)
When I play around with the parameters and if I submit via the "Try it out!" button, a mangled URL is generated which won't work in my case:

http://www.lorem.ipsum:80/takearest/v1/search/label/any?q=politik&qt=contains&lang=de

As you can see, the subURI part "dbkzakat" is missing! The REST service is perfectly fine, it works, if you alter the URL so it will contain the subURI part.

To clarify, I added a screenshot :)

What's wrong here? Could you please have a look at it?

fireshot screen capture 024

Setting API key default value doesn't work immediately

Hello, I'm using this method to set API key default value:

GrapeSwaggerRails.options.before_action do |request|
  GrapeSwaggerRails.options.api_key_default_value = some_key
end

It fills the input, but it doesn't send the key. To force it to do so I need too trigger js change event on the input, e.g. add space, press enter, remove space, press enter again.

In the source code it looks like the only thing api_key_default_value does is setting the initial value of the input. It doesn't trigger change event that would actually update the key that is used.

Is it a bug or am I doing something wrong here? If it's a bug, I can prepare PR to fix it.

Documentation not loading. swagger_doc.json {"error":"Not Found"}

Below is the configuration I used to build API's using Grape.

But I am not able to build documentation using Swagger

Gems:

gem 'grape'
grape-0.13.0
gem 'grape-swagger-rails'
grape-swagger-rails-0.1.0
gem 'rack-cors', :require => 'rack/cors'
rack-cors-0.4.0

config/application.rb

require 'rack/cors'
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb') 
config.autoload_paths += Dir[Rails.root.join('app', 'api', '**', '*.rb')]

config/initializers/swagger.rb

GrapeSwaggerRails.options.url      = '/swagger_doc.json'
GrapeSwaggerRails.options.app_url  = "http://api.lvh.me:3000"

config/routes.rb

  constraints(subdomain: 'api') do
    mount API::Base => '/'
  end
  mount GrapeSwaggerRails::Engine, at: "/apidocs"

app/api/api/base.rb

require 'grape-swagger'
module API
  class Base < Grape::API
    default_format :json
    mount API::V1::Base

    add_swagger_documentation(
      api_version: "v1",
      hide_documentation_path: true,
      mount_path: "/",
      hide_format: true
    )
  end
end

Issue:

When I hit http://lvh.me:3000/apidocs. I'm getting below error below green Nav bar.

Can't read swagger JSON from http://api.lvh.me:3000/swagger_doc.json

When I hit http://api.lvh.me:3000/swagger_doc.json. Getting below response.

{"error":"Not Found"}

I am not able to figure out what am doing wrong. Need help in rendering Swagger documentation with grape framework.

http://stackoverflow.com/questions/33843077/grape-swagger-documentation-not-loading

Default content-type for generated PUT request

Hi guys,

I'm using grape-swagger-rails (0.3.0) to generate the documentation for a JSON API. I have an issue with all the actions expecting a payload in JSON format : indeed, the documentation generates a request body with the application/x-www-form-urlencoded format, and my API only handles application/json format.

capture d ecran 2017-04-03 a 17 49 43

Therefore, all the "Try it out" actions on the documentation for POST/PUT/PATCH requests are non-functional.

I've tried to manually add a Content-Type header in the GrapeSwaggerRails initialization section, but it doesn't seem to be taken into account :

GrapeSwaggerRails.options.headers[ 'Content-Type' ] = 'application/json'

Am I missing something in the configuration of my endpoints / of grape-swagger-rails here ? I've found nothing around here in the documentation.

EDIT: actually it looks like the payload is correctly understood by my API endpoint on POST and PATCH, but not on PUT requests... in case it helps. Any clues ? When I click "Try it out", I get this in the console for a PUT request only :

capture d ecran 2017-04-03 a 18 02 25

Pass through all Swagger-UI options to more fully support customization

Currently grape-swagger-rails has hard-coded support for passing through a few of the Swagger-UI options from the grape-swagger-rails initializer to the SwaggerUi initializer, in the index.html.erb file. Good examples of this include the docExpansion option, and the validatorUrl option. Here's a link to a recent pull request that added the validatorUrl option: #46.

@dblock rightfully pointed out that it would be better if we could come up with a clean way to pass through ALL of the Swagger-UI options, to completely support the features of Swagger-UI. Then we could strip out all the special case code that we currently have for supporting these options piecemeal.

There's a complete list of Swagger-UI options here: https://github.com/swagger-api/swagger-ui#parameters. I wonder if we might be best off making some kind of a whitelist of supported parameters to pass through, rather than just automatically passing through any and all options that are set. It will require a little more maintenance since when new options are added they would have to be added to the whitelist, but it might head off potential security issues.

Another point in favor of using some kind of list of supported parameters... it looks like the Swagger-UI params don't use a completely consistent case. Most are lowerCamelCase, but at least one (dom_id) is snake_case, which means that automatically converting from snake_case in the grape_swagger_rails.rb initializer to lowerCamelCase will fail in that case. Seems that a list showing how to translate from the Ruby name for the parameter to the JavaScript name for the parameter may be needed.

grape-swagger compatibility

Hi,

I wanted to discuss the "out of the box" compatibility of grape-swagger and grape-swagger-rails. It seems that when you install grape-swagger-rails (0.1.0) while using grape (0.11.0) and grape-swagger (0.10.1), you need to set options that aren't obvious from the README.

The first error I encountered was that when you setup grape-swagger-rails, there is an flash of errors that override each other and end with:

swagger_doc' from path http://api.rails-app.dev:3000/swagger_doc/swagger_doc.json (server returned undefined)

The other flashed errors are the same message but swagger_doc replaced with your resource. From the rails log, I was able to see that it was requesting a resource that was suffixed with .json

Started GET "/swagger_doc/swagger_doc.json" for 127.0.0.1 at 2015-04-03 16:14:20 -0700

ActionController::RoutingError (No route matches [GET] "/swagger_doc/swagger_doc.json"):

But out of the box, grape-swagger only creates urls of the form (notice no .json):
/swagger_doc/swagger_doc

By changing
add_swagger_documentation
to:

add_swagger_documentation(format: :json)

I was able to resolve the problem.

I propose that one or more of the following happens:

  1. The README for grape-swagger is changed.
  2. The README for grape-swagger-rails is changed.
  3. The code in grape-swagger automatically assumes the format of :json.
  4. Something better that the authors know. :)

I'm happy to send a PR anywhere for anything. I'm going to ping @dblock because he is so awesome and responds to everything grape related.

The following issues are relevant:
https://github.com/tim-vandecasteele/grape-swagger/issues/190
https://github.com/tim-vandecasteele/grape-swagger/issues/197

Make googlefonts optional

Thanks for this great tool!

Is it possible to add an option to disable google font? There are some places in the world hard to access google service 😿

current_user is undefined in before filter

Hi, thanks for your nice work.
I am going to implement Authentication and Authorization for my Swagger UI.
After checking the documentation, I decided to use current_user inside GrapeSwaggerRails.options.before_filter.
Unfortunately it says current_user is undefined.
I am currently using clearance gem for authentication.

Regards
Oleg

Customizing look of swagger?

Hi, I need to brand swagger so that it fits in with the organisation I am working for. How do I go about doing this without forking the gem?

Thanks

GrapeSwaggerRails::ApplicationController inherits ActionController::Base

Hi there!

In modern Rails versions all controllers inherit from ApplicationController, but GrapeSwaggerRails::ApplicationController inherits ActionController::Base. By this reason methods that are defined at ApplicationController are not accessible from GrapeSwaggerRails context.

For example, if we have defined a method current_user in Rails ApplicationController

# application_controller.rb

class ApplicationController < ActionController::Base

  def current_user
    User.find(session[:user_id])
  end

end

If we use method current_user in a before_filter hook as described here, we have an error:

  GrapeSwaggerRails.options.before_action do |request|
    GrapeSwaggerRails.options.api_key_default_value = current_user.api_token
  end
  undefined local variable or method `current_user' for #<GrapeSwaggerRails::ApplicationController:0x007f88a1c5ac48>

This problem could be solved if GrapeSwaggerRails::ApplicationController inherits standard ApplicationController

Thanks for reading this!

Taking swagger-ui from rails-assets

Hey, this is a very nice project, but keeping swagger-ui dist files in the repository among with rake-task for downloading them makes me sad. I have an idea to add swagger-ui dist as a dependency in Gemfile. I can even make a PR with that. What do you think?

Hash > Hash > Array[Integer] isn't properly reflected in the Data Type column of the UI

Hi,

Considering the following resource, It seems to generate an improper swagger Data Type Example Value:

module Test
  module V1
    class Ping < Grape::API
      resource :ping do
        desc "Are you alive!", tags: ['tools']
        params do
          requires :test, type: Hash, documentation: { param_type: 'body' } do
            requires :hash, type: Hash do
              requires :int_array, type: Array[Integer]
            end
          end
        end
        post do
          'pong'
        end
      end
    end
  end
end

This shows the following:

{
  "test": [
    {
      "hash": [
        {
          "int_array": 0
        }
      ]
    }
  ]
}

However I would expect:

{
  "test": {
    "hash": {
      "int_array": [0]
    }
  }
}

The model is also wrong:

postControlPing {
  test (Array[inline_model_11])
}
inline_model_11 {
  hash (Array[Inline Model 1], optional)
}
Inline Model 1 {
  int_array (integer)
}

it should be:

postControlPing {
  test (inline_model_11)
}
inline_model_11 {
  hash (Inline Model 1, optional)
}
Inline Model 1 {
  int_array (Array[integer])
}

It seems like the array breaks it and is set on every parent member instead of the element iteself.

As a quick fix i'm using:

        params do
          requires :test, type: Hash, documentation: { param_type: 'body' } do
            requires :hash, type: Hash do
              requires :int_array, type: Object, documentation: { type: 'Array[Integer]' }
            end
          end
        end

This prints out:

{
  "test": {
    "hash": {}
  }
}

and

postControlPing {
  test (inline_model_11)
}
inline_model_11 {
  hash (Inline Model 1, optional)
}
Inline Model 1 {
  int_array (Array[Integer])
}

The example isn't perfect but i can fix that with a note in the description of the endpoint.
Thanks

Problem with file uploading at 0.1.1 version

I have got issue with uploading files at 0.1.1 version of grape-swagger-rails
This is screenshot of swagger with grape-swagger-rails version 0.1.1
2015-10-12 13 49 31
This errors comes after sending request:
2015-10-12 13 50 19
2015-10-12 13 50 45

And this is with 0.1.0
2015-10-12 13 51 38

Click of "example" doesnt populate the input field

API is Rails Api based
I have the css and javascript in the asset pipeline and they are being generated and are loading to the browser. However when viewing a api document page and clicking on the yellow box to populate the input field with the example it does nothing. Normally for swagger ui this does work. See petstore working example ... http://petstore.swagger.io/#!/pet/addPet and click the yellow example payload.

It doesnt seem to work on my grape-swagger-rails version :(

When i hit the swagger root page (not the page in question) I get a js error in console
screen shot 2017-03-04 at 8 59 11 am

When i visit the actual endpoint page (api/users) screen renders fine. Switch from model/example works. But clicking the yellow example box - does nothing :(

Array of object is not built properly

I have this definition in my API

params do
requires :daycare_attributes, type: Hash do
  requires :departments_attributes, type: Array do
    requires :name
  end
end

The UI shows
image

Which is fine. But when I try it, it doesn't build the array properly. In the curl, it built something like

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d \
'daycare_attributes[departments_attributes]%5Bname%5D=Math&daycare_attributes[departments_attributes]%5Bname%5D=Phsyics' \
'http://localhost:3000/api/'

To pass the grape parameter validation. It must be

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' -d \
'daycare_attributes[departments_attributes][][name]=Math&daycare_attributes[departments_attributes][][name]=Phsyics'\
 'http://localhost:3000/api/'

Both curl and UI xhr failed to pass the validation.

Update rubygems version?

It looks like this project is still being actively developed. Any chance of updating rubygems?

Swagger options not serialized correctly in view

The view file includes options for swagger via

<html data-swagger-options="<%= GrapeSwaggerRails.options.marshal_dump.to_json %>">

but that is not html_safe, so the contents of the json string get escaped - we end up with &quot; inside our json object.

I'm not sure if this is specific to rails 4, but I made it work properly locally by changing the above to

<html data-swagger-options='<%== GrapeSwaggerRails.options.marshal_dump.to_json %>'>

This API is using a deprecated version of Swagger

After updating grape-swagger to 20.1 version swagger won't load documentation. When I have opened Javascript console, it shows error messages:

 This API is using a deprecated version of Swagger!  Please see http://github.com/wordnik/swagger-core/wiki for more info
Uncaught TypeError: Cannot read property 'length' of undefined swagger-ui.min.self-bfe16e3….js?body=1:217

Uncaught TypeError: Cannot read property 'definitions' of null

Hi authors,

I followed the 'grape-swagger-rails' documentation and the /swagger_doc.json initial page loads fine from swagger ui as follows:

swagger-first-page-ok

But apart from this page all other requests, I am getting one of the 2 errors

1st Error: Unable to Load SwaggerUI
(I am testing '401 Unauthorised' page works or not with swagger documentation)

For this response Swagger ui is not loading and showing the following error:
Unable to Load SwaggerUI
apidoc:50 401 : http://g_m.lvh.me:3000/content/api/v1/activities/23

swagger-401-unauthorised

2nd Error: Uncaught TypeError: Cannot read property 'definitions' of null

(I am testing '200 Created' page works or not with swagger documentation)
For all other successful requests (200) where I am sending json response back, occurs the following error:
Uncaught TypeError: Cannot read property 'definitions' of null

screen shot 2016-06-15 at 1 57 54 pm

screen shot 2016-06-15 at 1 58 10 pm

NOTE: I implemented this on a Rails Engine that is mounted on '/content'

I tried a lot, feeling that any configuration I missed to include all these urls in swagger ui. But nothing I can found. Reply me if you have a solution for this else please fix this issue as soon as possible.

Deprecation warning in Rails5

DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from block (2 levels) in <module:ClassMethods> at /Users/moe/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0/lib/abstract_controller/callbacks.rb:191)
Processing by GrapeSwaggerRails::ApplicationController#index as HTML
  Rendering /Users/moe/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/grape-swagger-rails-0.2.1/app/views/grape_swagger_rails/application/index.html.erb

URI::InvalidURIError in GrapeSwaggerRails::Application#index

Currently, I face a problem when I try to access http://localhost:3000/swagger and it raise error
URI::InvalidURIError in GrapeSwaggerRails::Application#index
bad URI(is not URI?): file-digest:///home/../app/assets/config/grape_swagger_rails
Does anyone know how to fix this issue?

Paths with grape-swagger-rails 0.9

With previous applications running 0.7.2, I would initialise with
GrapeSwaggerRails.options.url = '/swagger_doc.json'

However, with v 0.9, had to replace that with
GrapeSwaggerRails.options.url = '/swagger_doc'
and remove the .json to get things to work

Is it possible to "skin" the swagger docs

Hi,

Is there some way of setting up up Swagger Docs rails so it can use other methods in my application?
Also I would like to reuse my default layout in app/views/layouts/application.html.haml, is this possible?

I do have swagger docs working and displaying but I would like to "skin" it to look like the rest of my application.

Many thanks

P.S relatively noobie rails developer

Adding API Key doesn't appear to do anything

Hi,

My initializer looks something like this:

GrapeSwaggerRails.options.tap do |o|
  # other details omitted
  o.before_filter do |request|
    authenticate_with_http_basic do |user, pass|
      user == ENV['basic_auth_username'] && password == ENV['basic_auth_password']
    end
  end
  o.api_auth     = 'bearer'
  o.api_key_name = 'Authorization'
  o.api_key_type = 'header'
end

When I fill in my API key and try to explore the API, my API returns that I'm not authenticated. Chrome headers show my response looks like this:

Remote Address:127.0.0.1:3000
Request URL:http://api.rails-app.dev:3000/users/me
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:application/json
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Type:application/json
Cookie:_Swyp_session=eUJVWkFkVDBsY0JUM2lsUlJmK1l3ekZSZkYzWkJob0RtdnZCeS9WVnRzMzYrSWZWY3IrRHk3OG5CWGRoblE1eWdCaEJSZEtQYU8rSk1yci9CLzJsZEFGQWNLYVBia01mbXNBeGViZkxkbWlhc3pDVXg5K0FFa2lJbzFMVTAvTlZKbVNOcmwzLzBwNHJaVVJUT2U0eVZRPT0tLWMwYkZDRVZjT3I0VjYwdzVXY05CakE9PQ%3D%3D--ce1311b8a602a03f272492ae3cdd2b9576bacced
Host:api.rails-app.dev:3000
Referer:http://api.rails-app.dev:3000/swagger
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/39.0.2171.65 Chrome/39.0.2171.65 Safari/537.36

The swaggerApi object doesn't appear to be including any authorization handlers either.

SwaggerApi {url: "http://api.rails-app.dev:3000/swagger_doc", debug: false, basePath: "http://api.rails-app.dev:3000/swagger_doc", authorizations: null, authorizationScheme: null…}

image

My Gemfile.lock looks like this:

    grape (0.10.1)
      activesupport
      builder
      hashie (>= 2.1.0)
      multi_json (>= 1.3.2)
      multi_xml (>= 0.5.2)
      rack (>= 1.3.0)
      rack-accept
      rack-mount
      virtus (>= 1.0.0)
    grape-entity (0.4.5)
      activesupport
      multi_json (>= 1.3.2)
    grape-swagger (0.10.1)
      grape (>= 0.8.0)
      grape-entity
    grape-swagger-rails (0.1.0)
      grape-swagger (>= 0.7.2)
      railties (>= 3.2.12)

I looked around in the code to try to debug this myself but I couldn't quite figure out where the options were being read.

How to prefill API key for swagger UI

I'm using:

  • Rails 4.2.6
  • Grape, Win Bouncer, Doorkeeper

How can I pre-fill API key for logged in user for swagger UI? The only way I figured out how to get the current token is by creating on separate rails app as an OauthClient. However, for convenience and in production I would like to prefill the api key in swagger UI. Or how can a logged in user get the api key easily?

wine_bouncer.rb:

WineBouncer.configure do |config|
  config.auth_strategy = :swagger

  config.define_resource_owner do
    User.find(doorkeeper_access_token.resource_owner_id) if doorkeeper_access_token
  end
end

swagger.rb:

GrapeSwaggerRails.options.url      = '/api/mobile/swagger_doc.json'
GrapeSwaggerRails.options.app_url  = 'https://www.domain.com'
GrapeSwaggerRails.options.api_key_name = 'access_token'
GrapeSwaggerRails.options.api_key_type = 'query'

how to override default assets?

I wanna to custom style for swagger,

I copy application.css from grape-swagger-rails and place into myapp/app/assets/stylesheets/grape_swagger_rails.

/*
*= require reset
*= require screen
*= require_self
*/

ul {
  margin-left: 10px;
}

but it throw error:

couldn't find file 'reset'

Pre-fill some inputs

I have some inputs that I'd like to pre-fill when a user is logged in like the user's CLIENT_TOEKN.
screenshot 2016-06-29 11 46 37

But I can't figure out how to do it.

Binary attachments render corrupt file

I am using a grape api and can render the attachment in my code just fine. However it does not appear to work in the swagger ui. There is a download link which opens a file that can not be displayed properly.

We both use createObjectURL with a blob, however the response type in swagger ui is a string while I am using an arraybuffer. When I change my code to use a string instead I get the same behavior as swagger ui.

Is there a way to specify the response type to be array buffer instead?

Detach Fork

This is a very minor issue.

Would ruby-grape considering detaching the fork from BrandyMint? It's a very minor ux issue because its constantly comparing the master of the two repos. I'm very grateful for BrandyMint's contributions and would support adding the original repo to the README.

To detach the fork and turn it into a standalone repository on GitHub, contact GitHub support.

https://help.github.com/articles/why-are-my-contributions-not-showing-up-on-my-profile/
https://github.com/contact

Don't know how to build task 'swagger_ui:dist:update'

rake swagger_ui:dist:update --trace
rake aborted!
Don't know how to build task 'swagger_ui:dist:update'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/task_manager.rb:62:in `[]'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:149:in `invoke_task'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:106:in `each'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:106:in `block in top_level'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:115:in `run_with_threads'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:100:in `top_level'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:78:in `block in run'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:176:in `standard_exception_handling'
/Users/tangmonk/.rvm/gems/ruby-2.1.5/gems/rake-10.4.2/lib/rake/application.rb:75:in `run'

How do I change heading in swagger?

How do I change heading in swagger

In swagger UI all the headings are having default messages like "user: Operations about user". Is there any way that I can customize the heading?

swagger_heading

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.