Giter VIP home page Giter VIP logo

scalar's Introduction

Scalar API Reference

CI Release Contributors GitHub License Discord

Generate interactive API documentations from Swagger files. Try our Demo

Screenshot of an API Reference

Features

  • Uses Swagger/OpenAPI spec files
  • Request examples for a ton of languages + frameworks
  • Has an integrated API client
  • Edit your Swagger files with a live preview
  • Doesn’t look like it’s 2011

Scalar Townhall on Thu Mar, 28th in Discord

Join us to see upcoming features, discuss the roadmap and chat about APIs with us. 💬

Table of Contents

Getting Started

From a CDN

<!doctype html>
<html>
  <head>
    <title>API Reference</title>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <!-- Add your own OpenAPI/Swagger spec file URL here: -->
    <!-- Note: this includes our proxy, you can remove the following line if you do not need it -->
    <!-- data-proxy-url="https://api.scalar.com/request-proxy" -->
    <script
      id="api-reference"
      data-url="https://petstore3.swagger.io/api/v3/openapi.json"
      data-proxy-url="https://api.scalar.com/request-proxy"></script>
    <!-- You can also set a full configuration object like this -->
    <!-- easier for nested objects -->
    <script>
      var configuration = {
        theme: 'purple',
      }

      var apiReference = document.getElementById('api-reference')
      apiReference.dataset.configuration = JSON.stringify(configuration)
    </script>
    <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
  </body>
</html>

You can also use the following syntax to directly pass an OpenAPI spec:

<script
  id="api-reference"
  type="application/json">
  {  }
</script>

If you’d like to add a request proxy for the API client (to avoid CORS issues):

<script
  id="api-reference"
  type="application/json"
  data-proxy-url="https://api.scalar.com/request-proxy">
  {  }
</script>

With Vue.js

The API Reference is built in Vue.js. If you’re working in Vue.js, too, you can directly use our Vue components. Just install them:

npm install @scalar/api-reference

And import the ApiReference component to your app:

<script setup lang="ts">
import { ApiReference } from '@scalar/api-reference'
</script>

<template>
  <ApiReference />
</template>

You can pass props to customize the API reference.

With React

The API Reference package is written in Vue, that shouldn’t stop you from using it in React though! We have created a client side (untested on SSR/SSG) wrapper in react.

import { ApiReferenceReact } from '@scalar/api-reference-react'
import React from 'react'

function App() {
  return (
    <ApiReferenceReact
      configuration={{
        spec: {
          url: 'https://petstore.swagger.io/v2/swagger.json',
        },
      }}
    />
  )
}

export default App

With Nextjs

Our Next.js handler makes it easy to render a reference, just add it to an Api route handler:

// app/reference/route.ts
import { ApiReference } from '@scalar/nextjs-api-reference'

const config = {
  spec: {
    url: '/swagger.json',
  },
}

export const GET = ApiReference(config)

Read more: @scalar/nextjs-api-reference

With Fastify

Our fastify plugin makes it so easy to render a reference, there’s no excuse to not have a documentation for your API.

await fastify.register(require('@scalar/fastify-api-reference'), {
  routePrefix: '/reference',
  configuration: {
    spec: () => fastify.swagger(),
  },
})

Actually, it’s executing the fastify.swagger() call by default (if available). So that’s all you need to add:

await fastify.register(require('@scalar/fastify-api-reference'), {
  routePrefix: '/reference',
})

We wrote a detailed integration guide for Fastify, too.

Read more about the package: @scalar/fastify-api-reference

With Platformatic

Good news: If you’re using a recent version of Platformatic, the Scalar API reference is installed and configured automatically.

With Hono

Our Hono middleware makes it so easy to render a reference:

import { apiReference } from '@scalar/hono-api-reference'

app.get(
  '/reference',
  apiReference({
    spec: {
      url: '/swagger.json',
    },
  }),
)

Read more: @scalar/hono-api-reference

With ElysiaJS

The @elysiajs/swagger plugin uses our API reference by default.

import { swagger } from '@elysiajs/swagger'
import { Elysia } from 'elysia'

new Elysia()
  .use(swagger())
  .get('/', () => 'hi')
  .post('/hello', () => 'world')
  .listen(8080)

// open http://localhost:8080/swagger

Read more about @elysiajs/swagger

With Express

Our Express middleware makes it so easy to render a reference:

import { apiReference } from '@scalar/express-api-reference'

app.use(
  '/reference',
  apiReference({
    spec: {
      content: OpenApiSpecification,
    },
  }),
)

Read more: @scalar/express-api-reference

With NestJS

Our NestJS middleware makes it so easy to render a reference:

import { apiReference } from '@scalar/nestjs-api-reference'

app.use(
  '/reference',
  apiReference({
    spec: {
      url: '/swagger.json',
    },
  }),
)

Read more: @scalar/nestjs-api-reference

With Docusaurus

Our Docusaurus plugin makes it easy to render API references. Simple add the following to your Docusaurus config

import type { ScalarOptions } from '@scalar/docusaurus'

plugins: [
  [
    '@scalar/docusaurus',
    {
      label: 'Scalar',
      route: '/scalar',
      configuration: {
        spec: {
          url: 'https://petstore3.swagger.io/api/v3/openapi.json',
        },
      },
    } as ScalarOptions,
  ],
],

For more information, check out the Docusaurus package

With AdonisJS

There’s a community package to generate OpenAPI files in AdonisJS and it comes with support for the Scalar API reference already.

We wrote a detailed integration guide for AdonisJS.

With Laravel

There’s a wonderful package to generate OpenAPI files for Laravel already. Just set the type to external_laravel (for Blade) or external_static (for HTML) and theme to scalar:

<?php
// config/scribe.php

return [
  // …
  'type' => 'external_laravel',
  'theme' => 'scalar',
  // …
];

We wrote a detailed integration guide for Laravel Scribe, too.

With Rust

There’s a wonderful package to generate OpenAPI files for Rust already. Just set the api_route to use Scalar to get started:

use aide::{
    axum::{
        routing::{get_with},
        ApiRouter, IntoApiResponse,
    },
    openapi::OpenApi,
    scalar::Scalar,
};
...
    let router: ApiRouter = ApiRouter::new()
        .api_route_with(
            "/",
            get_with(
                Scalar::new("/docs/private/api.json")
                    .with_title("Aide Axum")
                    .axum_handler(),
                |op| op.description("This documentation page."),
            ),
            |p| p.security_requirement("ApiKey"),
        )
        ...

Hosted API Reference

Wait, this is open source and you can do whatever you want. But if you want to add a nice, customizable guide, collaborate with your team and have everything served through a CDN, create an account on scalar.com.

Configuration

To customize the behavior of the API Reference, you can use the following configuration options:

  • isEditable: Whether the Swagger editor should be shown.
  • spec.content: Directly pass an OpenAPI/Swagger spec.
  • spec.url: Pass the URL of a spec file (JSON or YAML).
  • proxyUrl: Use a proxy to send requests to other origins.
  • darkMode: Set dark mode on or off (light mode)
  • layout: The layout to use, either of modern or classic (see #layouts).
  • theme: The them to use (see #themes).
  • showSidebar: Whether the sidebar should be shown.
  • customCss: Pass custom CSS directly to the component.
  • searchHotKey: Key used with CNTRL/CMD to open the search modal.
  • metaData: Configure meta information for the page.
  • hiddenClients: List of httpsnippet clients to hide from the clients menu, by default hides Unirest, pass [] to show all clients.
  • onSpecUpdate: Listen to spec changes with a callback function.

For detailed information on how to use these options, refer to the Configuration Section.

Layouts

We support two layouts at the moment, a modern layout (the default) and a Swagger UI inspired classic layout (we jazzed it up a bit though).

layouts

Themes

You don’t like the color scheme? We’ve prepared some themes for you:

/* theme?: 'alternate' | 'default' | 'moon' | 'purple' | 'solarized' |
'bluePlanet' | 'saturn' | 'kepler' | 'mars' | 'deepSpace' | 'none' */
<ApiReference :configuration="{ theme: 'moon' }" />

ℹ️ The default theme is … the default theme. If you want to make sure no theme is applied, pass none.

Advanced: Styling

Overwrite our CSS variables. We won’t judge.

:root {
  --theme-font: 'Comic Sans MS', 'Comic Sans', cursive;
}

We’re using the default- prefix for our variables to not overwrite your variables. You can use all variables without a prefix.

/* ✅ Good (without `default` prefix) */
--theme-font: 'Comic Sans MS', 'Comic Sans', cursive;
/* ❌ Bad (with `default` prefix) */
--default-theme-font: 'Comic Sans MS', 'Comic Sans', cursive;

Overwrite our night mode and day mode variables to build your own themes. Here are some of the basic variables to get you started:

basic-scalar-variables

.light-mode {
  --theme-color-1: #121212;
  --theme-color-2: rgba(0, 0, 0, 0.6);
  --theme-color-3: rgba(0, 0, 0, 0.4);
  --theme-color-accent: #0a85d1;
  --theme-background-1: #fff;
  --theme-background-2: #f6f5f4;
  --theme-background-3: #f1ede9;
  --theme-background-accent: #5369d20f;
  --theme-border-color: rgba(0, 0, 0, 0.08);
}
.dark-mode {
  --theme-color-1: rgba(255, 255, 255, 0.81);
  --theme-color-2: rgba(255, 255, 255, 0.443);
  --theme-color-3: rgba(255, 255, 255, 0.282);
  --theme-color-accent: #8ab4f8;
  --theme-background-1: #202020;
  --theme-background-2: #272727;
  --theme-background-3: #333333;
  --theme-background-accent: #8ab4f81f;
}

Or get more advanced by styling our sidebar!

scalar-sidebar-variables

.light-mode .sidebar {
  --sidebar-background-1: var(--theme-background-1);
  --sidebar-item-hover-color: currentColor;
  --sidebar-item-hover-background: var(--theme-background-2);
  --sidebar-item-active-background: var(--theme-background-2);
  --sidebar-border-color: var(--theme-border-color);
  --sidebar-color-1: var(--theme-color-1);
  --sidebar-color-2: var(--theme-color-2);
  --sidebar-color-active: var(--theme-color-2);
  --sidebar-search-background: var(--theme-background-2);
  --sidebar-search-border-color: var(--theme-border-color);
  --sidebar-search-color: var(--theme-color-3);
}
.dark-mode .sidebar {
  --sidebar-background-1: var(--theme-background-1);
  --sidebar-item-hover-color: currentColor;
  --sidebar-item-hover-background: var(--theme-background-2);
  --sidebar-item-active-background: var(--theme-background-2);
  --sidebar-border-color: var(--theme-border-color);
  --sidebar-color-1: var(--theme-color-1);
  --sidebar-color-2: var(--theme-color-2);
  --sidebar-color-active: var(--theme-color-2);
  --sidebar-search-background: var(--theme-background-2);
  --sidebar-search-border-color: var(--theme-border-color);
  --sidebar-search-color: var(--theme-color-3);
}

Community

We are API nerds. You too? Let’s chat on Discord: https://discord.gg/8HeZcRGPFS

Packages

This repository contains all our open source projects and there’s definitely more to discover.

Package Description
@scalar/api-client-proxy API request proxy
@scalar/api-client API testing client
@scalar/api-reference beautiful API references
@scalar/cli CLI to work with OpenAPi files
@scalar/echo-server a server that replies with the request data
@scalar/express-api-reference Express plugin
@scalar/fastify-api-reference Fastify plugin
@scalar/hono-api-reference Hono middleware
@scalar/mock-server fake data based on an OpenAPI specification files
@scalar/nestjs-api-reference NestJS middleware
@scalar/nextjs-api-reference Next.js adapter
@scalar/swagger-editor editor tailored to write OpenAPI files
@scalar/swagger-parser parse OpenAPI files

Contributors

hanspagel
hanspagel
tmastrom
tmastrom
marclave
marclave
hwkr
hwkr
cameronrohani
cameronrohani
amritk
amritk
geoffgscott
geoffgscott
ATREAY
ATREAY
Mohib834
Mohib834
mcollina
mcollina
mouhannad-sh
mouhannad-sh
Amorim33
Amorim33
dunklesToast
dunklesToast
FotieMConstant
FotieMConstant
Chinlinlee
Chinlinlee
soulchild
soulchild
sinh117801
sinh117801
dotfortun
dotfortun
SebastianBienert
SebastianBienert
Mason-Little
Mason-Little
ShadiestGoat
ShadiestGoat
IHIutch
IHIutch
jonataw
jonataw
Fdawgs
Fdawgs
danp
danp
chrislearn
chrislearn
sigpwned
sigpwned

Contributions are welcome! Read CONTRIBUTING.

License

The source code in this repository is licensed under MIT.

scalar's People

Contributors

amritk avatar atreay avatar cameronrohani avatar chinlinlee avatar chrislearn avatar danp avatar dependabot[bot] avatar dunklestoast avatar fotiemconstant avatar geoffgscott avatar github-actions[bot] avatar hanspagel avatar hwkr avatar ihiutch avatar jonataw avatar marclave avatar mason-little avatar mcollina avatar mohib834 avatar mouhannad-sh avatar sigpwned avatar sinh117801 avatar tmastrom 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

scalar's Issues

Clicking on any endpoint on the search modal don't do anything

Expected Behavior

When clicking any endpoint link on the search modal, user should navigate to the desired link

Actual Behavior

Nothing happens

Reproduction steps

1. Go to https://docs.scalar.com/swagger-editor
2. Click on the Petstore example
3. Click on the Search text input, so the modal appears, click on any endpoint
4. Nothing happens

Version

latest

What browsers are you seeing the problem on?

Chrome

[DOC-1237] Support application/x-www-form-urlencoded in requestBody

Expected Behavior

application/x-www-form-urlencoded can be used in the request body

Actual Behavior

Currently we only support application/json inside of https://github.com/scalar/scalar/blob/main/packages/api-reference/src/components/Content/ReferenceEndpoint/RequestBody.vue

Reproduction steps

Add a swagger file with a requestBody of not just application/json

Version

0.8.1

What browsers are you seeing the problem on?

No response

DOC-1237

Make CDN build smaller

The CDN build is huge. Most of it is probably Node polyfills.

✓ 1609 modules transformed.
dist/browser/standalone.js  5,250.08 kB │ gzip: 1,181.41 kB

Let’s try to make it smaller.

Debugging

npx vite-bundle-visualizer -c vite.cdn.config.ts

At the first glance those make it big:

  • @scalar/swagger-editor (make a build without the swagger editor?)
  • CodeMirror
  • icons (huge potential to reduce the build size)

Set the URL to the active sidebar item

Currently, the IntersectionObserver sets the URL. The URL is then set to the section that’s becoming visible, not to the active item (which is the first item in the sidebar, where the section visible).

Responses assumed to be from proxy

Expected Behavior

Loaded scalar from a CDN and not using a scalar request proxy. Issue a request. See the response.

Actual Behavior

The network inspector shows the response coming back successfully but the UI doesn't show it.

Reproduction steps

1. Find an operation
2. Issue a test request for it (maybe changing headers/etc to make it succeed)
3. See that only response duration is shown

Version

0.7.9

What browsers are you seeing the problem on?

Chrome

CSS reset isn’t included

We need some kind of CSS reset (no matter which, as long as we know what we’re building on). I just added a modern-normalize import recently, but instead of including it, it’s just kept as the import statement.

We need to make sure the import statement is resolved and the CSS is included, otherwise all projects need the reset as a dependency.

[DOC-1242] Mapping from OpenAPI Models -> Response/Request payloads

Expected Behavior

Currently there's no way to tell if a request/body is being mapped from an OpenAPI/Swagger model. We might want to have some indicator to if/what is being mapped. Maybe a chip/pill that links to the model?

OpenAPI models are listed, but there is no visible mapping between request's payload and response to them (request shows copy of the model, response shows only example/generated-example )

Actual Behavior

No mapping to openapi models from request/responses

Reproduction steps

load a swagger spec :) and you can see the lack of mapping✨

Version

latest

What browsers are you seeing the problem on?

No response

DOC-1242

ReferenceError: process is not defined

Hi,

I tried to use the ApiReference in a new Vue project, but I'm getting. ReferenceError: process is not defined.

Reproduction steps:

  • Create a new Vue project: npm create vue@latest.
  • Install dependencies: npm install.
  • Add @scalar/api-reference: npm install @scalar/api-reference
  • Replace the contents of App.vue with:
<script setup>
import { ApiReference } from '@scalar/api-reference'
</script>

<template>
  <ApiReference spec-url="https://petstore.swagger.io/v2/swagger.json" />
</template>
  • Start the project: npm run dev.
  • Open the page & check the console.

Initially, I tried to do it in my existing project and got this error, so I thought maybe I'll try with a brand new project but it was still not working. I followed the exact steps above.

I can provide a reproduction repo if needed.

I'm on Node v18.17.1.

Create an Express plugin

Would be nice to have an Express middleware which is easy to add to an existing Express setup.

The response examples don’t generate example arrays

Example schema:

{
  "schema": {
    "type": "array",
    "items": {
      "type": "object",
      "properties": {
        "apr": {
          "type": "number",
          "minimum": 0
        },
        "date": {
          "type": "string"
        },
        "vault_address": {
          "type": "string"
        }
      },
      "required": [
        "apr",
        "date",
        "vault_address"
      ]
    }
  }
}

Add anchors to headings

Let’s add anchor icons to all headings (Markdown, operations, models).

They should copy the link to the section on click.

secuirty param using securitySchemes in path does not show up in UI

Expected Behavior

In the openapi spec (3.0.0), the path has security object it does not show up in the UI.

Actual Behavior

Path level security headers should be shown like is redocly or swagger editor
Screenshot 2023-10-18 at 12 21 46 PM

Reproduction steps

  1. Go to https://www.frogment.com/edit/raj-debug/cashfree-oct18.json#paths/_orders.yaml
  2. Click on Preview
  3. Open a new tab an go to https://www.frogment.com/edit/raj-debug/cashfree-oct18.json#components/securitySchemes/XClientID.yaml

Version

CDN

What browsers are you seeing the problem on?

Firefox

Proper CDN strategy (published on release, not on push to main)

Current approach was to use Netlify to build on push to main.

But what we really want is a standalone build on release.

I’m now trying to add the standalone build to the existing @scalar/api-reference package and use a public CDN. But that doesn’t work yet.

Description of properties not loading using CDN version

Expected Behavior

OpenAPI version: 3.0.0
This is a property name and it has a description.

NewPet:
  type: "object"
  required:
    - "name"
  properties:
    name:
      type: "string"
      description: "some desc"
    tag:
      type: "string"

UI does not load description
Screenshot 2023-10-18 at 11 37 22 AM

Full html

<!DOCTYPE html>
<html>
  <head>
    <title>Swagger Petstore - API Reference</title>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1" />
    
  </head>
  <body>
    <!-- Add your own OpenAPI/Swagger spec file URL here: -->
    <script
      id="api-reference"
      data-url="/json/raj12/pet_store.json"></script>
    <script src="https://www.unpkg.com/@scalar/api-reference"></script>
  </body>
</html>```



### Actual Behavior

Description to come in the UI

 


### Version

CDN

### What browsers are you seeing the problem on?

Chrome, Firefox

Make the use of window.location as the base url an option

We’re using the current url (window.location) as a fallback for the server URL. There’s only one use case, where that’s helpful: When rendering the reference through the fastify plugin.

We should only use that as the fallback for the fastify plugin and need to make it a config option.

[DOC-1223] Ensure parent tag gets opened when sidebarItem is changed

Expected Behavior

I can navigate to an endpoint from the sidebar or endpoint preview list when a tag is closed

Actual Behavior

No navigation happens

Reproduction steps

load petstore example
navigate to a closed tag
click an endpoint from the list of endpoints of a tag
wont navigate

Version

0.7.9

What browsers are you seeing the problem on?

Chrome

DOC-1223

Path parameters render incorrectly

The spec allows parameters to be defined on each operation or at the path level. When using them at the path level, like below. Scalar attempts to parse/render the parameters as a method/operation, instead of applying the parameters to every operation under that path.

openapi: '3.0.2'
info:
  title: Broken Params
  version: '1.0'
paths:
  /items/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema:
          type: string
    get:
      summary: Get Item
    put:
      summary: Update Item
    delete:
      summary: Delete Item
Screenshot 2023-10-13 at 2 57 56 PM Screenshot 2023-10-13 at 3 00 48 PM

add GitHub issue templates

Suggestion:

Get Help
If you can't get something to work the way you expect, open a question in our discussion forums.

Feature Request
Suggest any ideas you have using our discussion forums.

Bug Report
If you've already asked for help with a problem and confirmed something is broken, create a bug report.

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.