Skip to content

Code Samples

Code Samples allow you to showcase API request examples in multiple programming languages. This feature helps API consumers understand how to integrate with your API using their preferred language.

You can customize:

  • Which languages to display (langs)
  • Available languages for selection (availableLangs)
  • How code is generated for each language (generator)

Custom Languages

For example, you can add Bru Markup Language to the list of languages to show and available languages to select from and a generator to convert the request object to Bru code.

Example

markdown
---
aside: false
outline: false
title: vitepress-openapi
---

<script setup lang="ts">
import { onBeforeMount, onBeforeUnmount } from 'vue'
import { useTheme, generateCodeSample } from 'vitepress-openapi/client'

onBeforeMount(() => {
    useTheme({
        codeSamples: {
            // List of languages to show in Code Samples section.
            langs: [
                'bruno',
                ...useTheme().getCodeSamplesLangs(),
            ],
            // List of available languages to select from.
            availableLanguages: [
                {
                    lang: 'bruno',
                    label: 'Bruno',
                    highlighter: 'plaintext',
                },
                ...useTheme().getCodeSamplesAvailableLanguages(),
            ],
            defaultLang: 'bruno',
            generator: async (lang, request) => {
                if (lang === 'bruno') {
                    return generateBruRequest(request)
                }
    
                return generateCodeSample(lang, request)
            },
        },
    })
})

onBeforeUnmount(() => {
    useTheme().reset()
})

function generateBruRequest(request) {
  const { url, method, headers, body, query } = request;

  const methodLower = method.toLowerCase();

  const queryString = query && Object.keys(query).length
    ? `${url}?${new URLSearchParams(query).toString()}`
    : url;

  const headersSection = headers && Object.keys(headers).length
    ? `headers {\n${Object.entries(headers)
        .map(([key, value]) => `  ${key}: ${value}`)
        .join('\n')}\n}`
    : '';

  const bodySection = body
    ? `body {\n  ${JSON.stringify(body, null, 2).replace(/\n/g, '\n  ')}\n}`
    : '';

  const bruRequest = `${methodLower} {
  url: ${queryString}
}

${headersSection}

${bodySection}
`;

  return bruRequest
        .trim()
        .replace(/\n{2,}/g, '\n\n') // Remove extra newlines
}
</script>

<OASpec />

Preview

The Argentine Rock Legends is an example OpenAPI specification to test OpenAPI tools and libraries. Get all the data for all artists.

Inspired by Scalar Galaxy

Resources

  • https://github.com/enzonotario/vitepress-openapi
  • https://github.com/OAI/OpenAPI-Specification

Markdown Support

All descriptions can contain tons of text Markdown. If GitHub supports the syntax, chances are we’re supporting it, too. You can even create internal links to reference endpoints.

Examples

Blockquotes

I love Argentine Rock. <3

Tables

Feature Availability
Markdown Support

Accordion

<details>
  <summary>Using Details Tags</summary>
  <p>HTML Example</p>
</details>

Images

Yes, there’s support for images, too!

Placeholder image

Contact

Servers

https://stoplight.io/mocks/enzonotario/argentine-rock/122547792Mock Server

Get all artists

GET
/api/v1/artists

Get a list of all legendary Argentine Rock artists and explore their contributions to the music scene. You can get one using the GETGet an artist endpoint.

Parameters

Query Parameters

limit

The number of items to return

Typeinteger
Examples
102050
format"int64"
default10
offset

The number of items to skip before starting to collect the result set

Typeinteger
Examples
123456
format"int64"
default0

Responses

Success Response

The request was successful and returns a list of artists.

Response Format

The response includes:

  • A data array containing artist objects
  • Pagination information

Note: You can use the pagination parameters to navigate through large result sets.

application/json
JSON
{
"data": [
{
"id": 1,
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}
],
"meta": {
"limit": 10,
"offset": 0,
"total": 100,
"next": "/artists?limit=10&offset=10"
}
}

Playground

Server
Variables
Key
Value

Samples


Add a new artist

POST
/api/v1/artists

Add a new legendary Argentine Rock artist. Make sure they truly deserve the title! You can view it later using the GETGet an artist endpoint.

Authorizations

bearerAuth
TypeHTTP (bearer)
or
apiKeyHeader
TypeAPI Key (header: X-API-Key)

Request Body

application/json
JSON
{
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}

Responses

Artist Created Successfully

The artist has been successfully added to our database.

Response Details

The response includes the complete artist object with:

  • A newly assigned unique id
  • All the information you provided in the request
application/json
JSON
{
"id": 1,
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}

Playground

Authorization
Body

Samples


Get an artist

GET
/api/v1/artists/{artistId}

Learn more about a specific Argentine Rock artist and their legacy. You can update it using the PUTUpdate an artist endpoint.

Parameters

Path Parameters

artistId*
Typeinteger
Required
Example1
format"int64"

Responses

Artist Found

The requested artist was found and returned successfully.

Response Format

The response includes the complete artist object with all available details:

  • id: Unique identifier for the artist
  • name: Full name of the artist
  • description: Biographical information
  • image: URL to the artist's photo
  • band: Primary band association
application/json
JSON
{
"id": 1,
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}

Playground

Variables
Key
Value

Samples


Update an artist

PUT
/api/v1/artists/{artistId}

Update the information of a legendary Argentine Rock artist. Make sure to provide accurate data. You can get the current data using the GETGet an artist endpoint.

Authorizations

bearerAuth
TypeHTTP (bearer)
or
apiKeyHeader
TypeAPI Key (header: X-API-Key)

Parameters

Path Parameters

artistId*
Typeinteger
Required
Example1
format"int64"

Request Body

application/json
JSON
{
"id": 1,
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}

Responses

Artist Updated Successfully

The artist information has been successfully updated in our database.

Response Details

The response includes the complete updated artist object with all the changes you made.

Note: All fields are returned in the response, even if you only updated some of them.

application/json
JSON
{
"id": 1,
"name": "Charly García",
"description": "One of the most influential rock musicians in Argentine history.",
"image": "https://cdn.rock-legends.com/photos/charly.jpg",
"band": "Sui Generis"
}

Playground

Authorization
Variables
Key
Value
Body

Samples


Deprecated

Delete an artist

DELETE
/api/v1/artists/{artistId}

This endpoint was used to delete artists. Unfortunately, that caused a lot of controversy. So, this endpoint is now deprecated and should not be used anymore. You can use the PUTUpdate an artist endpoint instead.

Authorizations

bearerAuth
TypeHTTP (bearer)
or
apiKeyHeader
TypeAPI Key (header: X-API-Key)

Parameters

Path Parameters

artistId*
Typeinteger
Required
Example1
format"int64"

Responses

Bad Request - Deprecated Endpoint

application/json
JSON
{
"type": "https://example.com/errors/generic-error",
"title": "Something went wrong here.",
"status": 403,
"detail": "Unfortunately, we can’t provide further information."
}

Playground

Authorization
Variables
Key
Value

Samples


Get all albums

GET
/api/v1/artists/{artistId}/albums

Get a list of all albums from a legendary Argentine Rock artist. You can add a new album using the POSTAdd a new album endpoint.

Parameters

Path Parameters

artistId*
Typeinteger
Required
Example1
format"int64"

Query Parameters

limit

The number of items to return

Typeinteger
Examples
102050
format"int64"
default10
offset

The number of items to skip before starting to collect the result set

Typeinteger
Examples
123456
format"int64"
default0

Responses

Albums Found

The request was successful and returns a list of albums for the specified artist.

Response Format

The response includes:

  • A data array containing album objects
  • Pagination information for navigating through large collections

Note: If the artist has no albums, the data array will be empty but the request will still return a 200 status code.

application/json
JSON
{
"data": [
{
"id": 1,
"name": "La Máquina de Hacer Pájaros",
"year": 1976,
"image": "https://cdn.rock-legends.com/photos/la-maquina.jpg"
}
],
"meta": {
"limit": 10,
"offset": 0,
"total": 100,
"next": "/artists?limit=10&offset=10"
}
}

Playground

Variables
Key
Value

Samples


Add a new album

POST
/api/v1/artists/{artistId}/albums

Add a new album to a legendary Argentine Rock artist. Make sure it's a masterpiece! You can view all albums using the GETGet all albums endpoint.

Authorizations

bearerAuth
TypeHTTP (bearer)
or
apiKeyHeader
TypeAPI Key (header: X-API-Key)

Parameters

Path Parameters

artistId*
Typeinteger
Required
Example1
format"int64"

Request Body

application/json
JSON
{
"id": 1,
"name": "La Máquina de Hacer Pájaros",
"year": 1976,
"image": "https://cdn.rock-legends.com/photos/la-maquina.jpg"
}

Responses

Album Created Successfully

The album has been successfully added to the artist's discography.

Response Details

The response includes the complete album object with:

  • A newly assigned unique id
  • All the information you provided in the request
  • The association with the artist
application/json
JSON
{
"id": 1,
"name": "La Máquina de Hacer Pájaros",
"year": 1976,
"image": "https://cdn.rock-legends.com/photos/la-maquina.jpg"
}

Playground

Authorization
Variables
Key
Value
Body

Samples


Authentication

Some endpoints are public, but some require authentication. We provide all the required endpoints to create an account and authorize yourself.


Create a user

POST
/api/v1/user/signup

Create a user account to access exclusive content about Argentine Rock legends. After signing up, you can access endpoints like GETGet all artists to explore the data.

Request Body

application/json
JSON
{
"name": "Carlos",
"email": "carlos@rock-legends.com",
"password": "i-love-rock"
}

Responses

User Created Successfully

Your account has been created and you can now access the Argentine Rock Legends API.

Response Details

The response includes your user information (excluding the password) and your API key for authentication.

Important: Save your API key securely as it will be needed for authenticated requests.

application/json
JSON
{
"id": 1,
"name": "Carlos",
"email": "carlos@rock-legends.com"
}

Playground

Body

Samples


Powered by VitePress OpenAPI

Using Icons with vitepress-plugin-group-icons

You can enhance your code samples by displaying custom icons for each programming language using the vitepress-plugin-group-icons plugin.

vitepress-plugin-group-icons is a markdown-it plugin that processes your Code Groups and only loads the icons you actually use to display them. On the other hand, vitepress-openapi is a set of Vue components for visualizing your OpenAPI Specification. Therefore, unless you also use the icons in your Markdown code, vitepress-plugin-group-icons will not load the icons that are used in the Vue components of vitepress-openapi.

In this case, you should instruct vitepress-plugin-group-icons to load certain icons by default, regardless of whether they are used in Markdown files or not.

You can do this by configuring the plugin as follows:

ts
import { defineConfigWithTheme } from 'vitepress'
import { groupIconVitePlugin } from 'vitepress-plugin-group-icons'

export default defineConfigWithTheme({
  // Your VitePress configuration...
  
  vite: {
    plugins: [
      groupIconVitePlugin({
        customIcon: {
          curl: 'simple-icons:curl', // Custom icon for curl.
        },
        defaultLabels: [ // Preload icons for specific labels.
          'curl',
          '.ts',
          '.js',
          '.py',
          '.php',
        ],
      }),
    ],
  },
})