Code Monkey home page Code Monkey logo

rapidoc's Introduction

MrinDoc logo

RapiDoc

Custom Element for Open-API spec viewing

Sponsored by Zuplo - Get a Stripe-like API experience for your customers in minutes - documentation, rate-limiting and API-key auth in minutes.

Features

  • Supports Swagger 2.0, OpenAPI 3.x.x
  • Works with any framework or with no framework
  • Allows making API calls
  • Better Usability,
    • all Models and Examples are expanded by default, eliminates the need to click and reveal.
    • Request fields are pre-populated with sample data
    • Takes only one click to make an API call
    • Request and response can be placed side-by-side for easy comparison
  • Branding and Personalization features makes it easy to follow any style guide
    • Comes with 2 Themes (Dark and Light)
    • Replace default logo with yours
    • Typography, allows changing fonts
    • Allows changing text-color, button-color, header-color and color of other UI elements
  • Plenty of customization options
    • Add external contents at the top and bottom of the document, you may add images, link, text, forms etc
    • Allows disabling API calling feature
    • Hide the header, so the user can't load any other OpenAPI Spec
    • Hide Authentication and provide your own pre-generated api-key
    • Embed it inside another HTML document
    • Use it inside another framework (react, vue, angular, lit-element)
    • Use JavaScript to change its attributes, and it will react to those changes
    • Style the element with standard css (change padding, position, border, margin )
  • Lightweight and fast
  • Load local json spec from the disk
  • Supported on Chrome, FireFox and Safari. (Not yet tested on Edge)

Documentation

Check out the usage and demos

Examples

Examples and Test cases

Build Process

# Clone / Download the project then
npm install

# build will generate rapidoc-min.js, this is the only file you will need.
# use it in the script tag of your html <script type="text/javascript" src="rapidoc-min.js"></script></body>
npm run build 

# for development use yarn serve (this will start an webserver at port 8080, then navigate to localhost:8080) 
npm run serve

Roadmap

  • โœ… Upgrade to use lit 2
  • Pre Rendering / Server Side Rendering (SSR) of RapiDoc
  • Improve PDF generation of OpenAPI spec Using RapiPDF
  • Create a Command Line interface (CLI) to make it automation friendly
  • Add localization support
  • Follow Web Content Accessibility Guidelines (WCAG 2)
  • Improve Homepage, Documentation and Examples
  • Create groundwork for automated testing
  • Create a live playground (Something like swagger editor)
  • Create a short animation/video to show how RapiDoc/RapiPDF works

rapidoc's People

Contributors

dependabot[bot] avatar dharmendra205111014 avatar domderen avatar fbacker avatar georgopoulosgiannis avatar jakul avatar jekkel avatar joshtwist avatar karlkilgi avatar levinguy avatar loraderon avatar madelinekosse avatar mhailstone avatar micheletriaca avatar molochiyivan avatar mrin9 avatar ntotten avatar patrickbowie avatar pranjan-togetherwork avatar ruchevits avatar snyk-bot avatar somuchforsubtlety avatar sroucheray avatar tobiaslieber avatar trebler avatar uzlopak avatar waldyrious avatar webdev-dsp avatar woutersioen avatar xeptore 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  avatar

rapidoc's Issues

Authorization is not work after change spec-url use loadSpec

Hi, I change spec-url value and use loadSpec to reload the new swagger file. But after change, the authorization is not work.

HTML:

<rapi-doc
  spec-url="/v2/api-docs"
  theme="dark"
  id="rapidoc"
  show-header="false"
  show-info="false"
>
  <header>
    <select name="" id="apis">
      <option value="/v2/api-docs">/v2/api-docs</option>
    </select>
  </header>
  <div style="height: 60px" slot="footer"></div>
</rapi-doc>

JS:

function setApiKey(){
    const docEl = document.getElementById('rapidoc');
    const authToken = JSON.parse(localStorage.getItem("authenticationToken") || sessionStorage.getItem("authenticationToken"));
    docEl.setAttribute('api-key-name','Authorization');
    docEl.setAttribute('api-key-location','header');
    docEl.setAttribute('api-key-value', `Bearer ${authToken}`);
  }

  document.addEventListener('DOMContentLoaded', e => {
    setApiKey();
    createSelector();

    const selector = document.getElementById('apis');
    selector.onchange = function(e) {
      const value = e.target.value;
      const docEl = document.getElementById('rapidoc');
      docEl.loadSpec(value);
    }
  })

Before change I can find Authorization in request header but cannot find it after change, and the request return 401.

AUTHENTICATION section's SET button does nothing for Bearer

The "SET" button in the "AUTHENTICATION" section does nothing when the security scheme is bearer:

...
"security": [
    {
      "Bearer": []
    }
  ]
...
"components": {
  "securitySchemes": {
        "Bearer": {
          "type": "http",
          "scheme": "bearer",
          "bearerFormat": "JWT",
          "description": "Some description"
        }
      }
}

If I use "type": "apiKey" and set the name and in fields the "SET" button will work though.

POST plaintext response not shown

Dunno if it's because the response is plain text or because it is a POST request, but the response text box stays blank despite seeing the response fine in the network monitor.

Example request includes readOnly fields

I have the following OpenAPI spec:

{
  "openapi": "3.0.2",
  "info": {
    "title": "example API",
    "version": "TODO",
    "description": "TODO"
  },
  "paths": {
    "/groups/": {
      "post": {
        "operationId": "createGroup",
        "parameters": [],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "required": [
                  "members"
                ],
                "properties": {
                  "id": {
                    "type": "integer",
                    "readOnly": true
                  },
                  "name": {
                    "type": "string",
                    "maxLength": 100
                  },
                  "members": {
                    "type": "array",
                    "items": {
                      "required": [],
                      "properties": {
                        "id": {
                          "type": "integer",
                          "readOnly": true
                        },
                        "name": {
                          "type": "string",
                          "maxLength": 100
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Expected behavior

A request example like so:

{
  "name": "string",
  "members": [
    {
      "name": "string"
    }
  ]
}

Actual behavior

A request example like this:

{
  "id": 0,
  "name": "string",
  "members": [
    {
      "id": 0,
      "name": "string"
    }
  ]
}

Note that the 'Model' tab correctly shows the read-only (R) flag for the id fields.

how to support GBK encoding annotation?

For some historical reasons, I have to use GBK encoding in my project. This makes the swagger document appear strange characters, how can I use RapiDoc in GBK encoding project? Thanks

Support for multiple request body types

First and foremost - this is an awesome tool - and produces better output than anything else I have found.. and just works. So thank you.

My API supports both application/json and application/x-www-form-urlencoded for some APIs. So I modeled it as:

    post:
      summary: Login to application
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Login"
          application/x-www-form-urlencoded:
            schema:             
              $ref: "#/components/schemas/Login"

This always renders as 'FORM DATA' and doesn't show the json request model.
Responses seems to work and render fine with multiple response types.

model does not represent required fields

In both the request and the response renderings there is no indication that a specific property is in the list of required properties. Take the (simple) case of login/password:

requestBody: description: | The request should contain the login and password of the user to be authenticated. content: application/json: schema: type: object properties: login: type: string example: johndoe password: type: string example: myFav0ritePassW0rd required: - login - password

there is no indication that these fields are required in the rendered model section.

Accordions?

Hi,

First, thanks for this theme ๐Ÿ‘

Once the API grows a bit, it becomes a large list of operations, which is "uncomfortable" to navigate quickly.

IMHO it would be nice to tag sections expandable/collapsible (like swagger ui for example). This would make navigation much more easy.

Path parameters are not automatically URL encoded

When trying a request using the documentation interface, path parameters must by manually URL encoded (eg. "/some/path" > "%2Fsome%2Fpath" or "Creme Brulee" > "Creme%20Brulee").

Is there a reason it is not automatically encoded?

Referencing named schemas in the model view

Hi,

I think the styling of RapiDoc is excellent, particularly when using the dark theme. But there's one behavior that currently prevents me from using the viewer. In the model view the viewer currently expands out everything. So if we reference a schema multiple times each use seems to get inlined. Which makes the model view extremely verbose in some examples. Is there an option I haven't noticed that changes this behavior so we see the top-level model and below that the models for the named schemas it references?

I haven't tried an example with a recursive schema yet, but wouldn't this cause problems for the current approach of fully expanding the model?

Thanks
Kevin

Response header support

First off, this is a fantastic viewer. Thank you!

I noticed that when I add headers to a given response object, that data is not included in the output.

I wanted to try to submit a PR for you to save you some time, but I really don't know how you would want to display the list of headers...

It does look like you collected all of the information into a variable at https://github.com/mrin9/RapiDoc/blob/master/src/components/api-response.js#L151 but there's no code to actually use the headersForEachRespStatus. Is this particular thing still a work in progress?

Here's the header code I was using -- it's parsing correctly into that variable as far as I can tell...

      responses:
        201:
          description: "Successfully created with location header set for new user"
          headers:
            Location:
              description: "URL for the newly created user"
              schema:
                type: string
                example: "http://localhost/api/user/1"

Suggestion: Display error when URL is invalid

If specified URL returns 404, then RapiDoc will display 'Loading ...' message forever.

I'm not an expert on JS, but I think it should be possible to display an error message saying 'URL % returned 404'

HTML code to trigger it:

  <!doctype html> <!-- Important: must specify -->
  <html>
  <head>
    <meta charset="utf-8"> <!-- Important: rapi-doc uses utf8 charecters -->
    <script src="https://unpkg.com/rapidoc/dist/rapidoc-min.js"></script>
  </head>
  <body>
    <rapi-doc 
      spec-url="https://google.com/give_me_yaml_please.yaml" 
    > </rapi-doc>
  </body> 
  </html>

Screenshot from 2019-07-03 08-59-25

relative $ref incorrectly resolved from root rather than current URI (Introduced in 4.2.1)

In 4.2.0, the following works for a open-api specification hosted in a sub path, such as https://docs.example.com/serviceA/

components:
  responses:
    collection:
      content:
        application/json:
          schema:
            ...
          example:
            $ref: 'examples/collection.json'

The example is correctly loaded from: https://docs.example.com/serviceA/examples/collection.json

In 4.2.1, the relative $ref is incorrectly resolved as relative to root as:

https://docs.example.com/examples/collection.json

WORKAROUND:

Downgrade to 4.2.0

Appending query string with & fail if API Key in query

https://github.com/mrin9/RapiDoc/blob/7f22f69d201cb964aab6fa8a56b564272f1e45cc/src/components/api-request.js#L514

The above line fails to build correct URL

Example: https://httpbin.org/get&api_key=test-key
Should be: https://httpbin.org/get?api_key=test-key

Suggested fixe(s)

Curl is incorrect when using relative spec-url

When using relative spec-url the curl is missing the server part:

<rapi-doc id="rapidoc" show-header="false" theme="dark" layout="row" spec-url="/swagger/spec-1.0.yml"></rapi-doc>
curl -X GET "/ds/assets?"

Proposal: use apicurio-data-models library to parse/analyze OpenAPI content

For reference, I work on the Apicurio Studio project, which is an open source API Designer. One of the outputs of that work is a standalone library called apicurio-data-models. It's a library that implements a data model for OpenAPI and AsyncAPI and includes the following useful features:

  • Reading/writing OpenAPI/AsyncAPI documents
  • Full visitor pattern for analyzing the data model
  • Transform OpenAPI 2 documents into OpenAPI 3
  • Validation of the data model
  • Command layer (with basic operational transformation capabilities) to apply changes to the data model (probably not useful to RapiDoc)

The source can be found here:
https://github.com/Apicurio/apicurio-data-models

The library is here in NPM:
https://www.npmjs.com/package/apicurio-data-models

It's is written in Java but transpiled into TypeScript/JavaScript - this is useful for us because Apicurio Studio's back-end is written in Java while the front-end is Angular ... and the same code powers both.

It has no dependencies and it replaces/deprecates the older oai-ts-core library.

We support RapiDoc as one of the renderers available in the "Preview Documentation" feature we have in Apicurio Studio. And that got us thinking that the work we did in the data model library might be useful to projects like this. So just wanted to make you aware of it in case it would be useful. :)

Either way, keep up the good work!

Support for array examples

I try to include examples for everything in my OAS definitions, including for arrays, but I'm not seeing the example array values in RapiDoc output. For example, this parameter definition:

    segmentIds:
      type: array
      description: IDs of segments that are included in the route.
      items:
        type: integer
      example:
        - 278
        - 279
        - 280
        - 281

Shows up as:

segmentIds:[
    0
]

It would be nice if example array values were displayed as all other example values are.

Feature Request: Ability to load API Spec from local string

Right now, as far as I can tell, you have to load the API Spec from a remote URL. I have a use case where I need to create a UI that someone can load / edit / create their API Spec in my app.

Is this a contribution you would accept? Or is there some other way to achieve this with the current implementation?

Option to switch location of summary and method/path

One key principle in information design is that you want to tell someone what something does before telling them how to do it. For example, "To add a customer, send this request." People approach documentation with their current task in mind, such as "I want to add a customer." Only someone who is already very familiar with an API can go to the documentation already knowing what method and path they are looking for.

Swagger UI just lists methods and paths, grouped by tags, but there isn't a single word of explanation anywhere until you click on something. Not good information design.

RapiDoc does better. The "path" view includes tag descriptions and method summaries. However, the summaries are off on the right, so the layout is "how before what," not "what before how."

Would it be possible to have an attribute that would cause the method summaries to appear on the left and the method/path on the right? Or maybe not show the method and path at all until the user clicks the summary. I know that must sound like heresy to a programmer, but it's actually common and respected in the world of API documentation. For example, Stripe documentation, PayPal API reference, Microsoft Azure API Reference.

Sorry this was so long -- just trying to describe and justify what I'm asking for.

Response example rendered incorrectly

Hi,

Firstly, thanks for making this repo! It does everything I want from a Swagger viewer, all in a lightweight package โค๏ธ

That said, I've found a small bug in the example response section, where the content from one example flows on top of the next one.

captura de tela 2019-02-15 as 09 21 55

Possible solution

There is a flex: 1 applied to the element. If I remove that, then the example renders much better:

captura de tela 2019-02-15 as 09 22 20

How to load fonts from CDN ?

This is more a question than an issue.
I am loading rapidoc from unpkg:

...
<body>
    <!-- Top navigation placeholder -->
    <rapi-doc id='rapidoc' show-header='false' theme='dark' layout='row'>
    </rapi-doc>
    <script src='https://unpkg.com/[email protected]/dist/rapidoc-min.js'></script>
...

And I saw that fonts are loaded from where index.html is served:

http://localhost:8080/rapidoc
https://unpkg.com/[email protected]/dist/rapidoc-min.js
http://localhost:8080/rapidoc-regular.woff2
http://localhost:8080/rapidoc-semi-bold.woff2

Is it possible to have the fonts taken from unpkg?

Thanks

Wrong server URL

Hi,

In my swagger definition, I have "host":"localhost:8080".

However, RapiDoc strangely declares that the API server is //api-docs//localhost:8080/

...which causes all "try" requests to fail of course.

AFAIK api-docs is solely the name of the swagger definition file.

Support for YAML format

I just stumbled onto RapiDoc and I'd like to check it out, but my OpenAPI definition is in YAML format, not JSON. All other swagger-related tools that I've come across work with both YAML and JSON, so it would be very nice if YAML could be added to RapiDoc.

Try button feedback

It would be nice for the "Try" button to provide some sort of feedback to prevent a user from clicking it more than once against an slow endpoint. (for instance, you could grey the button out on click until the request completes, and/or show some sort of progress graphic while the request is being executed)

Accept-Headers not properly sent in requests

I have a OpenAPI 2.0 doc that has both "application/json" and "application/xml" in the produces section at the api spec level. The generated requests don't include any Content-Type header, (which is actually required in my API to get the appropriate output). I don't necessairly need RapiDoc to be flexible in the output types the way SwaggerUI is, but could it send Content-Type="application/json" at a minimum?

How to add dynamic querystring parameters

Hi,
Does RapiDoc support sending dynamic query string parameters in the url?
As per the link https://stackoverflow.com/questions/49582559/how-to-document-dynamic-query-parameter-names-in-openapi-swagger, OpenAPI 3.x supports free-form query.
Does RapiDoc support it?

When I provide the following in my .yaml file:

openapi: 3.0.1
servers:
- url: https//sample
paths:
/users:
get:
parameters:
- in: query
name: params
schema:
type: object
# If the parameter values are of specific type, e.g. string:
additionalProperties:
type: string
# If the parameter values can be of different types
# (e.g. string, number, boolean, ...)
# additionalProperties: true
# style: form and explode: true is the default serialization method
# for query parameters, so these keywords can be omitted
style: form
explode: true

and provide the following as input for 'params' field:

additionalProperties=id

I get the output as "https://sample/users?params=additionalProperties=id".
Instead output should be as "https://sample/users?additionalProperties=id"

Not expanding the models in HTML.

I am trying to generate the HTML doc from swagger 2.0 spec using RapiDoc. My spec has definitions which refer to other definitions. In generated HTML doc, I do not see these referred objects being expanded inline. Please find the attached screenshot for this.

RapiDoc_1

RapiDoc2

In the example section, the reference definition is marked as "?" while in the "Model" section it is only showing up the type which is "object". I am expecting the fully expanded object definition here. Is it expected behavior?

Multiple API Key headers

Now it will use only first value

example

  "security": [
    {
      "ClientId": [],
      "PassKey": []
    }
  ],
  "components": {
    "securitySchemes": {
      "ClientId": {
        "type": "apiKey",
        "in": "header",
        "name": "Client-Id"
      },
      "PassKey": {
        "type": "apiKey",
        "in": "header",
        "name": "Pass-Key"
      }
    },

Request body in GET requests

Currently, GET and DELETE requests with rrequest bodies are forbidden:

Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

This is probably because the spec is "translated" in openAPI (where it is forbidden) instead of swagger v2 (where it is allowed).

Luckily, they noticed their "mistake" and will be allowing soon: OAI/OpenAPI-Specification#1937

I hope this tool will update accordingly. This ticket should serve as a reminder. ๐Ÿ˜ƒ

Arrays do not display examples

I didn't find a way to display array items as an example.

openapi: 3.0.0
info:
  description: Some description
  version: 0.0.1
  title: Some title

tags:
  - name: hello

paths:
  "/there":
    get:
      operationId: helloThereGet
      tags:
        - hello
      summary: Do something
      responses:
        200:
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ComplicatedResponse"
servers:
  - url: http://localhost:8080
components:
  schemas:
    ComplicatedResponse:
      type: object
      properties:
        stringProperty:
          type: string
          example: hello
        arrayStringProperty:
          type: array
          items:
            type: string
          example:
            - Some
            - Nice
            - Array

Expected result:
rapidoc_expected

Actual result:
rapidoc_actual

Consider setting value to default value if it exists

Say I have to following request body:

"requestBody": {
  "content": {
    "application/x-www-form-urlencoded": {
      "schema": {
        "type": "object",
        "properties": {
          "username": {
            "type": "string"
          },
          "password": {
            "type": "string",
            "format": "password"
          },
          "grant_type": {
            "type": "string",
            "default": "password"
          }
        }
      }
    }
  }
}

I'd expect the UI to have to value of the grant_type parameter to be set to password by default. Instead it's empty.

I tried this via: https://mrin9.github.io/RapiDoc/examples/example2.html
If the example uses the latest commit it should be on: ec5eb03bef7efe7845845a75b7e27eeecce0c36b.
If it uses the latest release it should be on: 5.2.2.
(I haven't found a way to determine the version from the example page itself)

Build error

Hi, I started playing around today and wondering how you're building this, I just did npm install and npx webpack, mostly looks like its building but I get an error, any advice much appreciated, looks great! Btw I'm looking to use this with Drupal 8 and Apigee.

ERROR in ./src/utils/parse-utils.js 172:9
Module parse failed: Export 'convertSpec' is not defined (172:9)
You may need an appropriate loader to handle this file type.
|   });
| }
> export { convertSpec };
 @ ./src/rapidoc.js 11:0-46 314:4-15
 @ ./src/index.js

Add a demo page

Would be great to see a demo of how it looks/works before setting it up.

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.