Skip to content

I want to add code sample to API

Kemal Erdem edited this page Dec 11, 2021 · 2 revisions
  1. Open a version of the docs you want to add code to.
  2. Select path. "Path" means the whole path to an API call. Sth. like paths -> /user -> post
  3. If there is no x-codeSamples property in this path create one like:
paths:
  /pet:
    post:
      [...other yaml attributes]
      x-codeSamples:
        - lang: 'C#'
          source: |
            if (response.statusCode == HttpStatusCode.Created)
            {
              // Successfully created
            }
  1. Done

Additional info

External files

If you want to add code samples that have more than a couple of lines of code you should try to add them as separate files. You can do this by replacing source value with $ref to the file:

- lang: PHP
  source:
    $ref: ../code_samples/PHP/echo/post.php

Now during the compilation, the content of the post.php file will be converter to string and put into the source attribute.

Languages

List of supported languages that can be put into lang attribute: js, json, c++, cpp, c#, objectivec, schell, bash, python, java, r, go.

Multiple examples from the same language

If you want to create more than one example from the same language you want to name them. To do that please use the name attribute like this:

      x-codeSamples:
        - lang: 'C#'
          name: 'v > 8'
          source: |
            using System;

            Console.WriteLine("Hello, world!");
        - lang: 'C#'
          name: 'v <= 8'
          source: |
            using System;
            
            // A version of the classic "Hello World" program
            class Program
            {
                static void Main(string[] args)
                {
                    Console.WriteLine("Hello, world!");
                }
            }

This will display two C# code samples one with the name v > 8 <C#> and the second with the name v <= 8 <C#>.