Search results

Fastest Way to Create an OpenAPI Specification Document (Using Stoplight Studio)

I need your input — I'm conducting a survey about trends in developer documentation for 2020. If you write docs for developers, please take this survey. (You can view the ongoing results viewed here.)

You can create an OpenAPI specification document in several ways: (a) auto-generating it from annotations in your source code, (b) coding it by hand in an editor such as the Swagger Editor, and (c) using a GUI editor such as Stoplight Studio. In this tutorial, I’ll walk through the third approach: using Stoplight Studio, a GUI editor for modeling your API, to quickly create your specification document.

Why use a GUI editor instead of coding everything by hand? All approaches have their merits. If you don’t work with the OpenAPI specification enough to remember all the fields and syntax for each property, or if you’re learning it for the first time, trying to get the syntax valid can be a real bear. Coding it by hand leads to many errors and forces you to spend a lot of time troubleshooting why the syntax is invalid. Using an editor helps you avoid these errors and focus instead on the content. For more, read this energetic post by Phil Sturgeon, who says Stoplight Studio is “an absolute game changer for API Design, and something I’ve been waiting for since I found out about it somewhere in 2018” — Reinventing API Design with Stoplight Studio.

Before we begin

Before we begin the tutorial, note the following:

  • Stoplight Studio isn’t the only GUI editor for creating OpenAPI specifications. You can also use OpenAPI-GUI, Apibldr, SwaggerHub’s visual editor, and others.
  • Although Stoplight has a commercial offering, their editor is free. In general, you can use the editor to create a valid specification and then choose the tool you want to use to render it (e.g., Stoplight, Redoc, Spectacle, Swagger UI, or some other display framework). Once you have a valid OpenAPI specification, the spec is tool agnostic and can be rendered by many different frameworks.
  • Stoplight’s platform gives you a nice path toward more comprehensive documentation, including not only API reference but also conceptual documentation and tutorial content. This lets you create a more seamless documentation experience for your readers.
  • Stoplight is one of the sponsors of my site. I would still recommend this approach regardless of any site sponsorship. It makes sense to use an editor when your content must conform to a highly technical syntax.
  • In this tutorial, we’ll use sample information from the OpenWeatherMap API (more specifically, the Current weather data endpoint), which is the same API we’ve been using in this course uses in other areas, such as the OpenAPI tutorial.
  • For full documentation, see the Stoplight Studio documentation.

Which version of Stoplight Studio?

Stoplight offers both a web app and a desktop app (Mac, Windows, or Linux). In this tutorial, you will use the web app version of Stoplight Studio because only the web app gives you the ability to publish your content online and try out requests (see Studio Desktop vs. Studio Web). However, you could also use the desktop app if desired (such as for scenarios where you’re working with private, unreleased data).

Activity: Stoplight Studio tutorial for creating an OpenAPI spec

In this tutorial, you’ll use Stoplight Studio to create a valid OpenAPI specification, using the OpenWeatherMap as the sample API.

Set up a project in Stoplight Studio

To get started in Stoplight Studio, you first create a GitHub repo to serve as the content source, and then you configure a new Stoplight Studio project to point to this GitHub source:

  1. Go to GitHub.com and create a repo, calling it something like “stoplight_openweathermap.” If you’ve never created a Github repo before, see Create a repo from GitHub’s docs. Copy the URL to your repo.
  2. Go to https://stoplight.io/studio/ and click On the Web.
  3. In the Open Git Project box, paste your GitHub URL, and then click Clone:

    Opening a Git project
    Opening a Git project
  4. When the project loads, in the left pane you’re prompted with the text “You do not have any APIs or models.” Click the API button in the sidebar.

    Creating a new API file
    Creating a new API file
  5. In the New API dialog box, name your API (e.g., “openweathermap”), and click Create. By default, the editor will use OAS 3.0 and YAML. (You can see more options, such as JSON or OAS 2.0, by clicking Advanced.)

    Stoplight Studio creates an OAS file (“OpenAPI Specification”) called, in this case, openweathermap.v1.yml and loads it as follows:

    Initial project in the Stoplight Studio editor
    Initial project in the Stoplight Studio editor
  6. Stoplight lets you toggle between a form and code view. The above screenshot shows the form view. Click the Code button in the upper-right to see the code automatically created:

    openapi: '3.0.0'
    info:
      title: openweathermap
      version: '1.0'
    servers:
    - url: http://localhost:3000
    paths: {}
    components:
      schemas: {}
    

    The empty curly braces {} are placeholders for content required for the spec to be valid. You will be populating the specification information here in the upcoming sections.

Enter the API name, version, description, and contact information

Let’s populate the API name, version, description, and contact information.

To populate the API info into Stoplight Studio, expand the API information section above and then complete the following:

  1. Insert the General API information.
  2. Insert the Contact information.
  3. Insert the License information.
  4. Insert the Servers information.
  5. Insert the Security information.
Creating the API overview
Creating the API overview

Note that with descriptions, Stoplight allows you to use Stoplight flavored Markdown. This Markdown version allows all the same tags as Commonmark but also includes some special tags for callouts, alerts, and other formatting.

Previewing the output

At any time, you can preview the OpenAPI documentation by clicking Publish and then sliding the Show Preview slider.

Previewing the docs
Previewing the docs

Enter the path and parameters

Now let’s enter the path and parameter information.

To enter paths and parameters:

  1. In the left sidebar, right-click the Paths folder and select New Path.

    New path
    New path
  2. Type weather and press enter. By default Stoplight creates a GET operation for the weather endpoint (which you could delete by right-clicking the path and selecting Delete GET Operation).
  3. Expand the Path and parameter information button above and enter the operation ID and description into Stoplight.
  4. Click the No tags button and enter a tag name to group the endpoint, such as “Weather endpoints.”
  5. Click + Security and select app_id.
  6. Click + Query Param and enter some of the parameter information from the above details as well. (Note that our sample API has only query parameters, no path parameters.)

    For this exercise, you don’t need to enter all the parameters, but at least enter the zip parameter.

Re-using parameters

Note that the OpenAPI spec allows to re-use parameters by storing the information in the components section. In the Stoplight Studio editor, currently you can’t directly add parameters into components using the GUI, but if you switch to the code view and manually enter the necessary code, then you can click the link button and select that reference.

For example, suppose you have the following inside components:

components:
  parameters:
    lon:
      name: lon
      in: query
      description: '**Longitude**. *Example: 139*. Longitude coordinate of the location of your interest. Must use with `lat`.'
      schema:
        type: string

Then you can click the link icon and select this reference:

Selecting references from components
Selecting references from components

You could first create the parameters using Stoplight’s GUI and then basically copy the same code (with minor adjustments) into the components section under a parameters sublevel.

Enter the responses and response schema

As a final step for this endpoint, you need to enter the response information. The response includes not only an example response but also the schema describing the response. The schema describes all possible values in the response, their data types, and whether the values are required or not.

Stoplight Studio’s editor has a GUI feature that lets you build your response. However, if you have a lengthy response, or if you’re unfamiliar with the JSON schema editor, it might be faster to use an external tool to automatically convert the response into the JSON schema first. This will give you a skeleton structure that you can then easily add more information to.

To enter the response in Stoplight Studio:

  1. Below the parameter section for the endpoint, click + Response. Then click Add Body.

    Adding a response
    Adding a response
  2. In your web browser (outside of Stoplight Studio), go to Generate JSON Schema in YAML format and paste in the response in the Input: JSON response section. Then click Submit. Copy the output.
  3. Return to Stoplight Studio and enter into the code view by clicking Code.
  4. Locate this code:

    responses:
      '200':
        description: OK
        content:
          application/json:
            schema:
              type: object
              properties: {}
            examples: {}
    
  5. Under schema, insert the generated output from the step 2, so that it looks like this:

    responses:
      '200':
        description: OK
        content:
          application/json:
            schema:
              type: object
              properties:
                coord:
                  type: object
                  properties:
                    lon:
                      type: number
                    lat:
                      type: number
                weather:
                  type: array
                  items:
                    type: object
                    properties:
                      id:
                        type: number
                      main:
                        type: string
                      description:
                        type: string
                      icon:
                        type: string
                base:
                  type: string
                main:
                  type: object
                  properties:
                    temp:
                      type: number
                    feels_like:
                      type: number
                    temp_min:
                      type: number
                    temp_max:
                      type: number
                    pressure:
                      type: number
                    humidity:
                      type: number
                visibility:
                  type: number
                wind:
                  type: object
                  properties:
                    speed:
                      type: number
                    deg:
                      type: number
                clouds:
                  type: object
                  properties:
                    all:
                      type: number
                dt:
                  type: number
                sys:
                  type: object
                  properties:
                    type:
                      type: number
                    id:
                      type: number
                    country:
                      type: string
                    sunrise:
                      type: number
                    sunset:
                      type: number
                timezone:
                  type: number
                id:
                  type: number
                name:
                  type: string
                cod:
                  type: number
    
            examples: {}
    

    When you insert this code block, even if you start with your cursor in the right place, the properties section will be left-aligned. Highlight that section and then click your Tab key a few times to indent it (or Shift+Tab to reverse indent). Make sure Stoplight doesn’t flag a validation error due to improper indentation.

  6. Switch back to the form view by clicking Form. Then observe that the schema is populated in the GUI editor:

    Schema editor populated in Form view
    Schema editor populated in Form view
  7. For each property, click the associated buttons in the same row to enter a description and example. Expand some of the Response information above button for this information.

    Entering descriptions in the GUI editor
    Entering descriptions in the GUI editor
  8. Click the Example tab and insert the example (from the same Response information section above). Call the example “Example.”

Reusing responses through components

The OpenAPI spec allows you to re-use common components. If you have a dozen different endpoints that all return the same information, you can create a “model” for that information (a model is a description of some object’s properties). In the code, this model will be stored the inside the components section. Anytime you see a $ref button in Stoplight, you can choose to use those sections stored in components (or “Models” in the Stoplight Studio interface).

A common scenario for re-use with responses might be 401 (unauthorized responses), which could conceivably be returned with each endpoint. To store this 401 response as a re-usable model:

  1. In the left sidebar, right-click Models and select New Model. Name the model “unauthorized_response”.
  2. You can use the JSON schema editor to create the properties of your re-usable model. Click the + object link twice to create two properties for the object. Name them cod and message. Change the data type for the first from string to integer.

    Creating a re-usable model
    Creating a re-usable model
  3. Return to your weather path and click + Response to create a new response.
  4. For the response code, select 401: Unauthorized.
  5. Click + Add Body.
  6. In the $Ref Target, click and select the unauthorized_response component:

    Selecting a re-usable model
    Selecting a re-usable model

Now you’re re-using the same model. As you work with larger APIs that re-use components, be sure to store your re-usable parts as models (or other subsections under components). As you can see from the options in the $Ref Target, you can even store these components outside the existing OpenAPI file:

Reference target storage options
Reference target storage options

Preview, test, and publish the output

Now that you’ve finished creating your OpenAPI spec, let’s preview, test, and publish your documentation.

  1. Click the Commit button, type a commit message, and then click Push. This creates a commit in your GitHub repo, which is where this content actually lives.
  2. Click the Publish button, and then slide the Preview toggle on.
  3. In the left sidebar, expand Weather Endpoints and click the Weather endpoint.
  4. Click the Try It tab.
  5. Select zip check box and enter a zip code. (At least one location parameter is required for the API to retrieve weather information.)
  6. Enter an API key into the value for the appid parameter. If you don’t have an OpenWeatherMap API key, you can use this: fd4698c940c6d1da602a70ac34f0b147.
  7. Click the Send button. If you’ve done everything correctly, you will see a response returned.

    Successful response using Stoplight
    Successulf response using Stoplight
  8. At this point, you can either publish or export your API documentation. To publish, click the Publish button. You will receive a URL for the published content.

    You can view my published API docs here.

  9. To export the OpenAPI content to publish in another tool, click Export OpenAPI. You can view mine here.

    If you don’t want to publish docs through Stoplight, you could use your OpenAPI definition with Redoc, Swagger UI, Spectacle, Docsy, and other tools. See Openapi.tools for a list of possibilities.

40% Complete

40/128 pages complete. Only 88 more pages to go.