### Install Guide Elements using npm
Source: https://guides.scalar.com/scalar/scalar-docs/components/tabs
Demonstrates how to install the Scalar guide elements package using npm. This is a common command-line operation.
```bash
npm install @scalar/guide-elements
```
--------------------------------
### Create a New React Project with Vite
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/react
Guides through setting up a new React project using Vite, a fast build tool. This involves running the create vite command and selecting React as the framework and JavaScript as the variant. It also includes steps for installing dependencies and starting the development server.
```bash
pnpm create vite my-awesome-app
```
```bash
? Select a framework: › - Use arrow-keys. Return to submit.
Vanilla
Vue
❯ React
Preact
Lit
Svelte
Solid
Qwik
Others
```
```bash
? Select a variant: › - Use arrow-keys. Return to submit.
TypeScript
TypeScript + SWC
❯ JavaScript
JavaScript + SWC
Remix ↗
```
```bash
cd my-awesome-app
pnpm install
pnpm run dev
```
--------------------------------
### Execute Scalar CLI Help Command
Source: https://guides.scalar.com/scalar/scalar-cli/getting-started
This command displays the help information for the Scalar CLI, providing an overview of available commands and their usage. It's useful for understanding the CLI's capabilities without needing to install it first.
```bash
npx @scalar/cli help
```
```bash
pnpm dlx @scalar/cli help
```
--------------------------------
### Create Documentation Folder and File
Source: https://guides.scalar.com/scalar/scalar-docs/github-sync
This snippet shows how to create a 'docs' folder and an example Markdown file ('introduction.md') using bash commands. This is the initial step for structuring your documentation content.
```bash
# Create a docs/ folder
mkdir docs
# Create an example file
echo "# Hello World" > docs/introduction.md
```
--------------------------------
### Install Scalar CLI Globally
Source: https://guides.scalar.com/scalar/scalar-cli/getting-started
Installs the Scalar CLI globally on your system, allowing you to run commands directly using 'scalar' instead of prefixing with 'npx'. The '--force' flag can be used to handle potential naming conflicts with other CLIs, such as the 'git' bundled 'scalar' CLI.
```bash
npm -g install @scalar/cli
```
```bash
npm -g --force install @scalar/cli
```
--------------------------------
### Markdown Task Lists Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Demonstrates the syntax for creating task lists, commonly used in GitHub Flavored Markdown. Allows users to track completion status of items.
```markdown
- [x] Completed task
- [ ] Pending task
- [ ] Another pending task
```
--------------------------------
### Run Docusaurus Playground Example
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/docusaurus
Executes a command to run the playground example for the Scalar Docusaurus integration. This is useful for testing the setup.
```bash
npm run playground
```
--------------------------------
### Markdown Headings Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Demonstrates the syntax for creating headings of different levels (1-6) in Markdown. This is fundamental for structuring content.
```markdown
# Heading 1
## Heading 2
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6
```
--------------------------------
### Create New Laravel Project
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Creates a new Laravel project named 'my-new-app' using the Laravel installer. This is an optional step if you are starting a new project.
```bash
laravel new my-new-app
```
--------------------------------
### Install Laravel Installer
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Installs the Laravel installer globally using Composer, allowing you to create new Laravel projects easily.
```bash
composer global require "laravel/installer=~1.1"
```
--------------------------------
### Markdown Blockquotes Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Illustrates the syntax for creating blockquotes, which are used to set apart quoted text from the main content. Supports multi-line blockquotes.
```markdown
> This is a blockquote
>
> It can span multiple lines
```
--------------------------------
### Markdown Code Blocks Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Demonstrates how to create fenced code blocks with optional language specification for syntax highlighting. This is crucial for displaying code snippets.
```javascript
function example() {
return "Hello, World!";
}
```
--------------------------------
### Fastify Swagger Setup
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
This section details the installation and basic setup of the @fastify/swagger package to generate OpenAPI 3.0 files for your Fastify application.
```APIDOC
## Install @fastify/swagger
### Description
Install the official package for generating OpenAPI 3.0 files.
### Command
```bash
npm install @fastify/swagger
```
## Basic Fastify Swagger Configuration
### Description
This code snippet shows the boilerplate required to set up the @fastify/swagger package in your Fastify application. It includes registering the plugin, defining basic OpenAPI information, and setting up a sample route with schema validation.
### Method
```javascript
import FastifySwagger from '@fastify/swagger'
import Fastify from 'fastify'
// Instantiate the framework
const fastify = Fastify({
logger: true,
})
// Set up @fastify/swagger
await fastify.register(FastifySwagger, {
openapi: {
info: {
title: 'My Fastify App',
version: '1.0.0',
},
components: {
securitySchemes: {
apiKey: {
type: 'apiKey',
name: 'apiKey',
in: 'header',
},
},
},
},
})
fastify.put(
'/example-route/:id',
{
schema: {
description: 'post some data',
tags: ['user', 'code'],
summary: 'qwerty',
security: [{ apiKey: [] }],
params: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'user id',
},
},
},
body: {
type: 'object',
properties: {
hello: { type: 'string' },
obj: {
type: 'object',
properties: {
some: { type: 'string' },
},
},
},
},
response: {
201: {
description: 'Successful response',
type: 'object',
properties: {
hello: { type: 'string' },
},
},
default: {
description: 'Default response',
type: 'object',
properties: {
foo: { type: 'string' },
},
},
},
},
},
(req, reply) => {
reply.code(201).send({ hello: `Hello ${req.body.hello}` })
},
)
// Serve an OpenAPI file
fastify.get('/openapi.json', async (request, reply) => {
return fastify.swagger()
})
// Wait for Fastify
await fastify.ready()
// Run the server
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.log(`Fastify is now listening on ${address}`)
})
```
### Description
This configuration registers the swagger plugin, defines API metadata, and sets up an example route (`PUT /example-route/:id`) with a detailed OpenAPI schema. It also includes a route (`GET /openapi.json`) to serve the generated OpenAPI specification.
```
--------------------------------
### Basic Scalar Configuration
Source: https://guides.scalar.com/scalar/scalar-docs/github-sync
This JSON snippet demonstrates the basic structure of the 'scalar.config.json' file. It includes the schema definition, a placeholder for a custom subdomain, and an example 'guides' entry pointing to a Markdown file.
```json
{
"$schema": "https://cdn.scalar.com/schema/scalar-config.json",
"subdomain": "YOUR_CUSTOM_SUBDOMAIN_HERE",
"guides": [
{
"name": "My awesome documentation",
"sidebar": [
{
"path": "docs/introduction.md",
"type": "page"
}
]
}
],
"references": []
}
```
--------------------------------
### Add SDK Installation Instructions with x-scalar-sdk-installation
Source: https://guides.scalar.com/scalar/scalar-api-references/openapi
The `x-scalar-sdk-installation` extension enables the inclusion of custom SDK installation instructions directly in the API header. It supports both Markdown formatted descriptions and shell script sources for installation commands.
```yaml
openapi: 3.1.0
info:
title: Example
version: 1.0
x-scalar-sdk-installation:
- lang: Node
description: Install our **Custom SDK** for Node.js from npm:
source: |-
npm install @your-awesome-company/sdk
```
--------------------------------
### Start Docusaurus Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/docusaurus
Navigates into the Docusaurus project directory and starts the development server. This command allows you to preview your Docusaurus site locally.
```bash
cd my-awesome-website
pnpm start
```
--------------------------------
### Markdown Lists Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Shows the syntax for creating both unordered (bulleted) and ordered (numbered) lists, including nested list structures. Essential for presenting sequential or related items.
```markdown
- Unordered list item
- Another item
- Nested item
- Another nested item
1. Ordered list item
2. Another item
1. Nested item
2. Another nested item
```
--------------------------------
### Publish Multiple APIs with Scalar CLI
Source: https://guides.scalar.com/scalar/scalar-registry/cli
Example of publishing multiple OpenAPI documents from a repository containing several APIs. Useful for scripting or CI/CD integration.
```bash
# Example: Publish multiple APIs
scalar registry publish ./apis/user-api/openapi.json --namespace myteam --slug user-api
scalar registry publish ./apis/product-api/openapi.json --namespace myteam --slug product-api
scalar registry publish ./apis/order-api/openapi.json --namespace myteam --slug order-api
```
--------------------------------
### Markdown Links and Images Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Provides the Markdown syntax for creating hyperlinks and embedding images. Links navigate users to external or internal resources, while images visually enhance content.
```markdown
[Link text](https://example.com)

```
--------------------------------
### Blog API with Seeding and Handlers
Source: https://guides.scalar.com/scalar/scalar-mock-server/data-seeding
Example demonstrating how to combine x-seed for initial blog post data and x-handler for defining GET and POST endpoints to list and create posts. It includes schema definitions for Post and NewPost, and uses faker for realistic data generation.
```yaml
openapi: 3.1.0
info:
title: Blog API
version: 1.0.0
paths:
/posts:
get:
summary: List all posts
operationId: listPosts
x-handler: |
return store.list('Post')
responses:
'200':
description: List of posts
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Post'
post:
summary: Create a new post
operationId: createPost
x-handler: |
return store.create('Post', {
id: faker.string.uuid(),
...req.body,
createdAt: new Date().toISOString()
})
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/NewPost'
responses:
'201':
description: Post created
content:
application/json:
schema:
$ref: '#/components/schemas/Post'
components:
schemas:
Post:
type: object
properties:
id:
type: string
title:
type: string
content:
type: string
author:
type: string
publishedAt:
type: string
format: date-time
createdAt:
type: string
format: date-time
x-seed: |
seed.count(10, () => ({
id: faker.string.uuid(),
title: faker.lorem.sentence(),
content: faker.lorem.paragraphs(4),
author: faker.person.fullName(),
publishedAt: faker.date.past().toISOString(),
createdAt: faker.date.past().toISOString()
}))
NewPost:
type: object
required:
- title
- content
properties:
title:
type: string
content:
type: string
author:
type: string
```
--------------------------------
### Run Mock Server with Scalar CLI
Source: https://guides.scalar.com/scalar/scalar-mock-server/getting-started
This command uses the Scalar CLI to start a mock server. It watches for changes in the 'openapi.json' file and automatically reloads the server. This is the quickest way to get a mock server running.
```bash
npx @scalar/cli document mock openapi.json --watch
```
--------------------------------
### Start Laravel Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Starts the built-in PHP development server for your Laravel application, making it accessible at http://127.0.0.1:8000.
```bash
php artisan serve
```
--------------------------------
### Install Fastify Project Dependencies
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Install the necessary dependencies for a new Fastify project, including Fastify itself.
```bash
npm init
npm install fastify
```
--------------------------------
### Install Laravel Scribe
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Installs Laravel Scribe as a development dependency using Composer. The --with-all-dependencies flag ensures all necessary packages are included.
```bash
composer require --dev --with-all-dependencies knuckleswtf/scribe
```
--------------------------------
### Basic Scalar Step Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/steps
Demonstrates the basic usage of the scalar-step component. It includes a required ID and an optional title. The content within the step can include code blocks or other rich text. This example shows how to install dependencies.
```html
First, install the required dependencies by running:
```bash
npm install @scalar/guide-elements
```
```
```markdown
:::scalar-step{ id="step-1" title="Install Dependencies"}
First, install the required dependencies by running:
```bash
npm install @scalar/guide-elements
```
:::
```
--------------------------------
### Markdown Tables Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Shows the Markdown syntax for creating tables with headers and rows. Tables are useful for organizing data in a structured, tabular format.
```markdown
| Header 1 | Header 2 | Header 3 |
|----------|----------|----------|
| Cell 1 | Cell 2 | Cell 3 |
| Cell 4 | Cell 5 | Cell 6 |
```
--------------------------------
### Run Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Starts the development server, often using nodemon for automatic restarts on file changes.
```bash
npm run dev
```
--------------------------------
### Install Scalar Mock Server
Source: https://guides.scalar.com/scalar/scalar-mock-server/getting-started
Installs the @scalar/mock-server package as a dependency for your Node.js project. This allows for programmatic integration and advanced usage within your applications.
```bash
npm install @scalar/mock-server
```
--------------------------------
### Authenticate with Scalar Platform (Web Login)
Source: https://guides.scalar.com/scalar/scalar-cli/getting-started
Initiates a web-based login process for authenticating with the Scalar platform. This method is typically used for local development environments and opens a browser for authentication.
```bash
scalar auth login
```
--------------------------------
### Install Swashbuckle.AspNetCore.Cli Tool (Shell)
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/net-aspnet-core/build-time-generation
Installs the Swashbuckle CLI tool required for build-time OpenAPI generation. This involves creating a tool manifest and then installing the CLI package.
```shell
dotnet new tool-manifest
dotnet tool install Swashbuckle.AspNetCore.Cli
```
--------------------------------
### ElysiaJS Setup with OpenAPI Plugin
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/elysiajs
Demonstrates how to initialize an ElysiaJS application and integrate the @elysiajs/openapi plugin. This setup automatically generates an OpenAPI specification and serves it at the '/openapi' endpoint. Dependencies include ElysiaJS and the @elysiajs/openapi plugin.
```typescript
import { Elysia } from 'elysia'
import { openapi } from '@elysiajs/openapi'
new Elysia()
.use(openapi())
.get('/', () => 'hello')
.post('/hello', () => 'OpenAPI')
.listen(3000)
// open http://localhost:3000/openapi
```
--------------------------------
### Install Scalar Fastify API Reference
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Installs the @scalar/fastify-api-reference package to render an API reference for the Fastify project.
```bash
npm install @scalar/fastify-api-reference
```
--------------------------------
### Basic Tabs Example Across Languages
Source: https://guides.scalar.com/scalar/scalar-docs/components/tabs
Demonstrates the creation of basic tabs with equivalent code examples in JavaScript, TypeScript, Python, Rust, Go, and C++. This snippet showcases how to structure tabbed content for different programming languages.
```javascript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet('World'));
```
```typescript
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet('World'));
```
```python
def greet(name):
return f"Hello, {name}!"
print(greet("World"))
```
```rust
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
fn main() {
println!("{}", greet("World"));
}
```
```go
package main
import (
"fmt"
)
func greet(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
func main() {
fmt.Println(greet("World"))
}
```
```cpp
#include
#include
std::string greet(const std::string& name) {
return "Hello, " + name + "!";
}
int main() {
std::cout << greet("World") << std::endl;
return 0;
}
```
--------------------------------
### Install Scalar SvelteKit Package
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/sveltekit
Installs the necessary package for integrating Scalar API Reference with SvelteKit using npm.
```bash
npm install @scalar/sveltekit
```
--------------------------------
### Install Fastify Swagger
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Installs the official @fastify/swagger package, which is used to generate OpenAPI 3.0 files.
```bash
npm install @fastify/swagger
```
--------------------------------
### Custom Response Handling Example (x-handler)
Source: https://guides.scalar.com/scalar/scalar-mock-server/custom-request-handlers
Demonstrates how to return custom JSON responses from an x-handler. This example fetches a list of posts and returns them along with metadata like total count and pagination information.
```javascript
const posts = store.list('Post')
return {
data: posts,
total: posts.length,
page: parseInt(req.query.page || '1'),
perPage: 10
}
```
--------------------------------
### Start AdonisJS Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/adonisjs
Navigates into the newly created AdonisJS project directory and starts the development server. This command is used to run your application locally during development.
```bash
cd my-awesome-app
npm run dev
```
--------------------------------
### Install Scalar API Reference with npm
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/vuejs
Installs the Scalar API Reference package using npm. This is the first step to integrate the component into your project. No specific runtime dependencies are mentioned beyond the package itself.
```bash
npm install @scalar/api-reference
```
--------------------------------
### Navigate to Project Directory
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Changes the current directory to the newly created Laravel project folder.
```bash
cd my-new-app
```
--------------------------------
### Tabs with Default Selection Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/tabs
Illustrates how to configure tabs to open with a specific tab selected by default. This example shows the implementation in JavaScript, TypeScript, and their corresponding markdown representations.
```javascript
const user = {
name: "John",
age: 30
};
```
```typescript
interface User {
name: string;
age: number;
}
const user: User = {
name: "John",
age: 30
};
```
```markdown
::::scalar-tabs{ default="TypeScript" }
:::
:::scalar-tab{ title="JavaScript" }
```javascript
const user = {
name: "John",
age: 30
};
```
:::
:::
:::scalar-tab{ title="TypeScript" }
```typescript
interface User {
name: string;
age: number;
}
const user: User = {
name: "John",
age: 30
};
```
:::
::::
```
--------------------------------
### Code Samples
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/net-aspnet-core/openapi-extensions
Add custom code examples for endpoints to assist developers in understanding usage.
```APIDOC
## POST /orders
### Description
Adds a custom code sample for creating an order using JavaScript and cURL.
### Method
POST
### Endpoint
`/orders`
### Parameters
### Request Body
- **order** (object) - Required - The order details.
### Request Example
```javascript
// Example for Minimal APIs
app.MapPost('/orders', CreateOrder)
.CodeSample("fetch('/orders', { method: 'POST', body: JSON.stringify(order) })",
ScalarTarget.JavaScript, "Create Order")
.CodeSample("curl -X POST /orders -d @order.json",
ScalarTarget.Shell, "Create with cURL");
// Example for Controllers
// Assumes a CodeSample attribute is applied similarly, though the example shows Minimal APIs syntax.
```
### Response
#### Success Response (200)
- **message** (string) - Success message.
#### Response Example
```json
{
"message": "Order created successfully."
}
```
---
## GET /products
### Description
Adds a custom JavaScript code sample for fetching products.
### Method
GET
### Endpoint
`/products`
### Parameters
### Request Body
### Request Example
```csharp
// Example for Controllers
[HttpGet]
[CodeSample("fetch('/products').then(r => r.json())", ScalarTarget.JavaScript)]
public IActionResult GetProducts() => Ok();
```
### Response
#### Success Response (200)
- **message** (string) - Success message.
#### Response Example
```json
{
"message": "Products retrieved successfully."
}
```
```
--------------------------------
### Install Microsoft.Extensions.ApiDescription.Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/net-aspnet-core/build-time-generation
Installs the necessary package for built-in OpenAPI document generation at build time in ASP.NET Core applications. This package automatically creates a JSON OpenAPI document in the project's output directory.
```shell
dotnet add package Microsoft.Extensions.ApiDescription.Server
```
--------------------------------
### Install OpenAPI to Markdown Converter
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/hono
Installs the `@scalar/openapi-to-markdown` package, which is used to convert OpenAPI documents into Markdown format for LLMs.
```bash
npm install @scalar/openapi-to-markdown
```
--------------------------------
### Install Scalar ASP.NET Core Packages
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/net-aspnet-core/openapi-extensions
Installs the necessary Scalar packages for either Microsoft.AspNetCore.OpenApi or Swashbuckle.AspNetCore.SwaggerGen to enable OpenAPI extensions.
```shell
dotnet add package Scalar.AspNetCore.Microsoft
```
```shell
dotnet add package Scalar.AspNetCore.Swashbuckle
```
--------------------------------
### Scalar YAML Configuration Example with UI Options
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/spring-boot
Provides an example of Scalar configuration in `application.yml` format, covering basic settings, UI customization (theme, layout, dark mode, custom CSS), content organization, and search shortcuts.
```yaml
scalar:
url: https://my-api-spec.json
path: /docs
enabled: true
theme: deepSpace
layout: modern
darkMode: false
hideSearch: false
customCss: "body { font-family: 'Arial', sans-serif; }"
operationTitleSource: path
tagSorter: alpha
operationSorter: method
documentDownloadType: both
searchHotKey: ctrl+k
```
--------------------------------
### Install Scalar API Reference for Astro
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/astro
Installs the Scalar API Reference component for Astro using npm. This is the initial step to integrate the component into your Astro project.
```bash
npm install @scalar/astro
```
--------------------------------
### Scalar YAML Configuration Example
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/spring-boot
Provides a comprehensive example of Scalar configuration in YAML format, covering authentication schemes (API Key, HTTP, OAuth2), preferred schemes, and UI customization options.
```yaml
scalar:
authentication:
# Security scheme names must match those defined in your OpenAPI document
# Single security scheme (simplified syntax)
preferredSecurityScheme: my-oauth-scheme
# Or multiple security schemes (list syntax)
# preferredSecuritySchemes:
# - my-oauth-scheme
# - my-api-key
# API Key security schemes
apiKey:
my-api-key:
name: X-API-Key
value: my-api-key-value
# HTTP security schemes (Basic and Bearer)
http:
my-basic-auth:
username: my-username
password: my-password
my-bearer-auth:
token: my-bearer-token
# OAuth2 security schemes
oauth2:
my-oauth-scheme:
defaultScopes:
- read
- write
flows:
authorizationCode:
clientId: my-client-id
clientSecret: my-client-secret
pkce: SHA-256
credentialsLocation: body
redirectUri: http://localhost:8080/callback
```
--------------------------------
### Install Fastify API Reference
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Install the Scalar API Reference plugin for Fastify using npm. This is the first step to integrating the API reference into your Fastify application.
```bash
npm install @scalar/fastify-api-reference
```
--------------------------------
### Install React Renderer for Scalar Plugins
Source: https://guides.scalar.com/scalar/scalar-api-references/plugins
Command to install the necessary package for using React components within Scalar API reference plugins. This includes the core React renderer and React itself.
```bash
npm install @scalar/react-renderer react react-dom
```
--------------------------------
### Run Scalar Mock Server with Docker (Quick Start)
Source: https://guides.scalar.com/scalar/scalar-mock-server/docker-image
These commands demonstrate the different ways to run the Scalar Mock Server in a Docker container. They cover using a command-line URL, environment variables for document content or URL, and volume mounting for local files. The server will be accessible on port 3000.
```bash
docker run -p 3000:3000 \
scalarapi/mock-server --url https://api.example.com/openapi.yaml
docker run -p 3000:3000 \
-e OPENAPI_DOCUMENT="$(cat ./openapi.yaml)" \
scalarapi/mock-server
docker run -p 3000:3000 \
-e OPENAPI_DOCUMENT_URL="https://api.example.com/openapi.yaml" \
scalarapi/mock-server
docker run -p 3000:3000 \
-v ./openapi.yaml:/docs/openapi.yaml:ro \
scalarapi/mock-server
```
--------------------------------
### Create Basic Fastify Project
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Set up a basic Fastify project, including installing Fastify and creating an initial JavaScript file with a simple route.
```javascript
// index.js
import Fastify from 'fastify'
// Instantiate the framework
const fastify = Fastify({
logger: true,
})
// Declare a route
fastify.get('/', function (request, reply) {
reply.send({ hello: 'world' })
})
// Run the server
fastify.listen({ port: 3000 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.log(`Fastify is now listening on ${address}`)
})
```
--------------------------------
### Basic Mock Server Usage in Node.js
Source: https://guides.scalar.com/scalar/scalar-mock-server/getting-started
Demonstrates how to use the @scalar/mock-server package within a Node.js application. It initializes a mock server with an OpenAPI document and starts an HTTP server using Hono. Includes custom request logging.
```typescript
import { serve } from '@hono/node-server'
import { createMockServer } from '@scalar/mock-server'
// Your OpenAPI document
const document = {
openapi: '3.1.1',
info: {
title: 'Hello World',
version: '1.0.0',
},
paths: {
'/foobar': {
get: {
responses: {
'200': {
description: 'OK',
content: {
'application/json': {
example: {
foo: 'bar',
},
},
},
},
},
},
},
},
}
// Create the mocked routes
const app = await createMockServer({
document,
// Custom logging
onRequest({ context, operation }) {
console.log(context.req.method, context.req.path)
},
})
// Start the server
serve(
{
fetch: app.fetch,
port: 3000,
},
(info) => {
console.log(`Listening on http://localhost:${info.port}`)
},
)
```
--------------------------------
### Scalar Mock Server Docker Compose Configuration
Source: https://guides.scalar.com/scalar/scalar-mock-server/docker-image
This is a complete `docker-compose.yml` example for setting up the Scalar Mock Server. It includes options for mounting local OpenAPI documents or using environment variables for document content or URL. The server is configured to restart automatically.
```yaml
services:
mock-server:
image: scalarapi/mock-server:latest
ports:
- "3000:3000"
volumes:
# Mount your OpenAPI documents directory
- ./documents:/docs:ro
environment:
# Optional: Use environment variable instead of volume mount
# OPENAPI_DOCUMENT: |
# openapi: 3.0.0
# info:
# title: My API
# version: 1.0.0
# Or use URL to fetch document
# OPENAPI_DOCUMENT_URL: https://api.example.com/openapi.yaml
restart: unless-stopped
```
--------------------------------
### Scalar Mock Server Configuration Methods
Source: https://guides.scalar.com/scalar/scalar-mock-server/docker-image
Demonstrates the four primary methods for providing an OpenAPI document to the Scalar Mock Server Docker image. Each method utilizes different approaches for inputting the API specification.
```bash
# Method 1: Command-Line URL Argument
docker run -p 3000:3000 \
scalarapi/mock-server --url https://api.example.com/openapi.yaml
# Method 2: Environment Variable (Content)
docker run -p 3000:3000 \
-e OPENAPI_DOCUMENT="$(cat ./openapi.yaml)" \
scalarapi/mock-server
# Method 3: URL Environment Variable
docker run -p 3000:3000 \
-e OPENAPI_DOCUMENT_URL="https://api.example.com/openapi.yaml" \
scalarapi/mock-server
# Method 4: Volume Mounting
docker run -p 3000:3000 \
-v ./documents:/docs:ro \
scalarapi/mock-server
```
--------------------------------
### Initialize Scalar Configuration File
Source: https://guides.scalar.com/scalar/scalar-docs/github-sync
This command creates an empty 'scalar.config.json' file, which is essential for configuring Scalar Docs. This file will later hold all project-specific settings.
```bash
touch scalar.config.json
```
--------------------------------
### Markdown Text Formatting Example
Source: https://guides.scalar.com/scalar/scalar-docs/components/markdown-support
Illustrates various text formatting options available in Markdown, including bold, italic, strikethrough, and inline code. These are used for emphasis and code snippets within text.
```markdown
**Bold text**
*Italic text*
~~Strikethrough text~~
`Inline code`
```
--------------------------------
### Authenticate with Scalar Platform (Token/Machine Based)
Source: https://guides.scalar.com/scalar/scalar-cli/getting-started
Authenticates with the Scalar platform using an API token. This method is suitable for CI/CD workflows and programmatic usage, where a pre-generated API key from the Scalar dashboard is provided.
```bash
scalar auth login --token 1234secrettoken5678
```
--------------------------------
### Validate OpenAPI File in GitHub Actions
Source: https://guides.scalar.com/scalar/scalar-cli/getting-started
A GitHub Actions workflow to validate an OpenAPI file. It checks out the repository, sets up Node.js, and then uses the Scalar CLI to validate a specified OpenAPI file. Remember to replace './my-openapi-file.yaml' with the correct path.
```yml
# .github/workflows/validate-openapi-file.yml
name: Validate OpenAPI File
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Validate OpenAPI File
# Replace "./my-openapi-file.yaml" with the correct path and filename for your project.
# Or: run `npx @scalar/cli init` and add the config file to your repository.
run: npx @scalar/cli document validate docs/openapi.yaml
```
--------------------------------
### Use Google Fonts with Custom Configuration
Source: https://guides.scalar.com/scalar/scalar-api-references/themes
Integrate fonts from Google Fonts, such as 'Roboto', by linking the font stylesheet and overriding CSS variables. The `withDefaultFonts: 'false'` configuration is crucial for this customization. This example demonstrates setting the theme and disabling default fonts.
```html
```
--------------------------------
### Create a New Docusaurus Project
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/docusaurus
Initializes a new Docusaurus website project using pnpm. This command sets up a basic Docusaurus site structure.
```bash
pnpm create create-docusaurus@latest my-awesome-website classic
```
--------------------------------
### Integrate Scalar API Reference using HTML and JavaScript
Source: https://guides.scalar.com/scalar/scalar-api-references/getting-started
This snippet shows how to embed the Scalar API Reference into an HTML page. It includes loading the Scalar JavaScript library from a CDN and initializing the API reference component with the OpenAPI document URL and a proxy URL.
```html
Scalar API Reference
```
--------------------------------
### Run Next.js Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/nextjs
Commands to navigate into a newly created Next.js project directory and start the development server. This allows you to view the default Next.js homepage locally.
```bash
cd my-awesome-app
npm run dev
```
--------------------------------
### x-codeSamples
Source: https://guides.scalar.com/scalar/scalar-api-references/openapi
Provides examples for popular HTTP clients and frameworks. Allows for custom examples, such as SDK usage.
```APIDOC
## x-codeSamples
We provide examples for a lot of popular HTTP clients and frameworks. For something completely custom, for example to show the use of your own SDK, you can use `x-codeSamples`:
```yaml
openapi: 3.1.0
info:
title: Val Town API
version: 1.0
paths:
'/v1/eval':
post:
+ x-codeSamples:
+ - label: ValTown JS SDK
+ lang: JavaScript
+ source: |-
import ValTown from '@valtown/sdk';
const valTown = new ValTown();
async function main() {
const valRunAnonymousResponse = await valTown.vals.runAnonymous({ code: 'console.log(1);' });
console.log(valRunAnonymousResponse);
}
main();
```
```
--------------------------------
### Mock Server with Authentication Handling
Source: https://guides.scalar.com/scalar/scalar-mock-server/getting-started
Shows how to configure the mock server to handle authentication based on security schemes defined in the OpenAPI document. It includes examples for Bearer Token and API Key authentication, returning 401 Unauthorized if credentials are not met.
```typescript
import { serve } from '@hono/node-server'
import { createMockServer } from '@scalar/mock-server'
// Your OpenAPI document
const document = {
openapi: '3.1.1',
info: {
title: 'Hello World',
version: '1.0.0',
},
paths: {
'/secret': {
get: {
security: [
{
bearerAuth: [],
},
{
apiKey: [],
},
],
responses: {
'200': {
description: 'OK',
content: {
'application/json': {
example: {
foo: 'bar',
},
},
},
},
'401': {
description: 'Unauthorized',
content: {
'application/json': {
example: {
error: 'Unauthorized',
},
},
},
},
},
},
},
},
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
apiKey: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key',
},
},
},
}
// Create the mocked routes
const app = await createMockServer({
document,
// Custom logging
onRequest({ context, operation }) {
console.log(context.req.method, context.req.path)
},
})
// Start the server
serve(
{
fetch: app.fetch,
port: 3000,
},
(info) => {
console.log(`Listening on http://localhost:${info.port}`)
},
)
```
--------------------------------
### Install Scalar NestJS API Reference
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/nestjs
Installs the Scalar API Reference package for NestJS using npm.
```bash
npm install @scalar/nestjs-api-reference
```
--------------------------------
### Run Fastify Development Server
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastify
Start the Fastify development server using the 'dev' script defined in package.json. This command typically uses nodemon for automatic restarts on file changes.
```bash
npm run dev
```
--------------------------------
### Install scalar-ninja
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/django-ninja
Install the scalar-ninja package using pip. This is the first step to integrate Scalar with your Django Ninja project.
```bash
pip install scalar-ninja
```
--------------------------------
### Install @scalar/nuxt module
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/nuxt
Installs the Scalar module for Nuxt.js using npx. This is the first step to integrate Scalar API reference into your Nuxt application.
```bash
npx nuxi module add @scalar/nuxt
```
--------------------------------
### Install Scalar FastAPI Plugin
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/fastapi
Installs the Scalar FastAPI plugin using pip. This is the initial step to integrate Scalar with your FastAPI application.
```bash
pip install scalar-fastapi
```
--------------------------------
### Create SQLite Database
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/laravel-scribe
Creates an empty SQLite database file in the database directory. This is specific to projects using SQLite as their database driver.
```bash
touch database/database.sqlite
```
--------------------------------
### Install @scalar/api-reference-react
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/nextjs
Installs the Scalar React API reference component package using npm. This is used for integrating API documentation with the Pages Router in Next.js.
```bash
npm install @scalar/api-reference-react
```
--------------------------------
### Initialize New AdonisJS Project
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/adonisjs
Creates a new AdonisJS project using npm. This step is optional if you already have a project. The process involves answering a few questions to configure the project, such as the starter kit, authentication, and database driver.
```bash
npm init adonisjs@latest my-awesome-app
```
--------------------------------
### Basic Scalar Configuration Example
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/spring-boot
Shows basic Scalar configuration properties including the OpenAPI spec URL, context path, and enablement. It also includes UI customization options like theme, layout, dark mode, and custom CSS.
```properties
# Basic configuration
scalar.url=https://my-api-spec.json
scalar.path=/docs
scalar.enabled=true
# UI customization
scalar.theme=deepSpace
scalar.layout=modern
scalar.darkMode=false
scalar.hideSearch=false
scalar.customCss=body { font-family: 'Arial', sans-serif; }
# Content organization
scalar.operationTitleSource=path
scalar.tagSorter=alpha
scalar.operationSorter=method
scalar.documentDownloadType=both
# Search and navigation
scalar.searchHotKey=ctrl+k
```
--------------------------------
### Install @scalar/nextjs-api-reference
Source: https://guides.scalar.com/scalar/scalar-api-references/integrations/nextjs
Installs the Scalar Next.js API reference package using npm. This package is essential for rendering API documentation within your Next.js application.
```bash
npm install @scalar/nextjs-api-reference
```