This guide was originally created and published by Tom Johnson on his website, I’d Rather Be Writing, and you can find the original content here.
In this tutorial, we will walk through using Stoplight for modeling an API. We will create a valid OpenAPI description, using the OpenWeatherMap as the sample API. With Stoplight, you can design, document, and build APIs faster. For a higher-level introduction to the OpenAPI specification, see Introduction to the OpenAPI specification.
Using a visual editor
Before we get started, let’s address an initial question about the approach we’re taking. When creating your OpenAPI specification document, why should you use a visual/GUI editor, which hides the code (unless you toggle the Code View open) instead of coding every detail of the spec by hand?
All approaches have their merits. But 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 in the raw code can be challenging. Coding by hand leads to many errors and forces you to spend a lot of time troubleshooting invalid syntax.
Using an editor helps you avoid these errors and focus instead on the content. The less time you spend fiddling with syntax and more time working on content, the better the outcome of the API design and the documentation. Stoplight lets you switch into the code view to work in that mode when you want, and switch back into the visual view when you want. This gives you the best of both worlds.
Before we begin
This tutorial should take about 30 minutes to an hour. No special technical knowledge is required.
What you’ll build
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 other tutorials, such as the OpenAPI tutorial.
Here’s the documentation output that you’ll build in this tutorial:
Stoplight provides a variety of options for working with projects — you can create a Stoplight project from scratch or connect to a Git repository and commit and publish your changes using a Git workflow. In this tutorial, you’ll take the simplest path: using the web editor and creating a Stoplight project. But recognize that you have more options for how you approach projects.
Step 1: Set up a project in Stoplight
- Go to https://stoplight.io/welcome
- Follow the on-screen instruction to sign up, create a workspace, and then log in to the workspace.
- Click the + (Add project) button at the top to add a new project. Give the project a name, and then click Create API Project.
The Stoplight editor opens. The left pane says, “You do not have any APIs or models.”
- Click the API button in the sidebar.
- In the New API dialog box, name your API (e.g., “openweathermap”). By default, the editor will use OpenAPI v3.1 and YAML – leave the defaults as is. Click Create.
Stoplight creates an OpenAPI (OAS) specification file called openweathermap.yml and loads it:
- Stoplight lets you toggle between a form and code editor. The above screenshot shows the Form view. Click the Code button in the upper-right corner to see the code automatically created.
The sample code includes some content for some fictitious user endpoints called /users/{userid} and /user.
You could simply paste in a valid OpenAPI spec into the Code view, and it would populate the Form view. But presumably you don’t already have an OpenAPI spec to paste into the code — this is why you’re using the editor, to build out the specification document.
- You can seamlessly switch between Form and Code views. Add a word in the Form view, switch to the Code view and find it, then remove it from the Code view and see how it updates in the Form view.
- Select users/{userId} under the Paths folder, and then click the Preview button in the upper-right corner to see what the content would look like when published:
The ability to switch views between Form, Code, and Preview gives you a lot of authoring power.
- Click the Form button to switch back to the Form view.
Step 2: Enter the API overview information
In this section, you will populate the fields in the API Overview section, which include the version, name, description, security, contact, license, and other general details. For this tutorial, We've prepared sample information for you to easily insert into the Stoplight Editor. (Note: In the sample information in the blue expandable sections, titles are in [brackets] for fields that don't have names.)
To populate the API overview:
- In the Stoplight sidebar, click API Overview.
- Enter information in each form field using information provided in the gray section below:
Sample API overview information block
API overview information
- [version, green square]: 2.5
- [page title]: OpenWeatherMap API
- Summary: Get the current weather
- Description …: Get the current weather, daily forecast for 16 days, and a three-hour-interval forecast for 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format.
Note: This sample Swagger file covers the current endpoint only from the OpenWeatherMap API.
Note: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the id parameter) will provide the most precise location results.
Servers
Security schemes
- left drop-down menu: apiKey
- key: app_id
- name: appid
- right drop-down menu: query
Global security +
- Select + Add global security
- Select app_id
Contact
License
Note: The Markdown source formatting in the sample text is intentional. When you copy and paste in the source, Stoplight will convert the Markdown into HTML when displaying the published page. Also note that Stoplight allows you to use Stoplight-flavored Markdown, which allows all the same tags as CommonMark but also includes some special tags for callouts, alerts, and other formatting.
When finished, the form should look as follows:
- Now that you entered information for the first section, check out how it looks. Click the Preview button in the upper-right corner. It should look as follows:
Tip: If you are seeing the Preview window side-by-side with the Form or Code view, you can make your browser window smaller so you can view the Preview window in full size.
- Click the Form button to return to the Form view.
Step 3: Enter the path and parameter information
Now enter the path and parameter information:
- In the sidebar, right-click the Paths folder and select New Path.
- Type weather and press enter.
By default Stoplight creates a GET operation for the weather endpoint. In our case, this works out great because this endpoint has a GET endpoint. But if not, you could just click the other operations available to create details for those operations.
You can remove the default /users/{userid} and /user and endpoints. Right-click each endpoint and select Delete Path.
- In the main window (not sidebar), change the path’s title from “Your GET endpoint” to “weather.”
- Click the Tags button in the upper-left corner and add a tag called “Weather endpoints.”
This tag will group the endpoints in the sidebar by this tag into a collapsed section called “Weather endpoints.” This is how you build navigation hierarchy for your endpoints. You won’t see this grouping until you publish your API, though. Here’s a screenshot of what that grouping will look like:
- In the Description field, add the description for this endpoint. Use the gray section below to get a description to paste here.
Sample path information
- /weather
- [Operation]: GET
- Operation ID: get-weather
- Description: Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations.
- In Stoplight, click the + Query Param button to expand the query parameters options. (Note that our sample API has query parameters only, no path parameters.) See the gray section below for sample query parameter information. Then populate all the query parameter information into the Stoplight editor.
Sample query parameter information
ZIP CODE
- Name: zip
- [Data type]: string
- Description…: Zip code. Search by zip code. Example: 95050,us. Please note that if the country is not specified, the search uses USA as a default.
UNITS
- Name …: units
- [Data type]: string
- Description…: Units. Example: imperial. Possible values: standard, metric, and imperial. When you do not use the units parameter, the format is standard by default.
- Other Properties: enum: standard, metric, imperial
CITY NAME
- Name …: q
- [Data type]: string
- Description…: City name. Example: London. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by a comma; use ISO 3166 country codes.
CITY ID
- Name …: id
- [Data type]: string
- Description…: City ID. Example: 2172797. You can call by city ID. The API responds with the exact result. The List of city IDs can be downloaded here. You can include multiple cities in this parameter — just separate them by commas. The limit of locations is 20. Note: A single ID counts as a one API call. So, if you have city IDs, it’s treated as 3 API calls.
LATITUDE
- Name …: lat
- [Data type]: string
- Description…: Latitude. Example: 35. The latitude coordinate of the location of your interest. Must be used with lon.
LONGITUDE
- Name …: lon
- [Data type]: string
- Description…: Longitude. Example: 139. The longitude coordinate of the location of your interest. Must be used with lat.
LANGUAGE
- Name …: lang
- [Data type]: string
- Description…: Language. Example: en. You can use lang parameter to get the output in your language. We support the following languages that you can use with the corresponded lang values: Arabic - ar, Bulgarian - bg, Catalan - ca, Czech - cz, German - de, Greek - el, English - en, Persian (Farsi) - fa, Finnish - fi, French - fr, Galician - gl, Croatian - hr, Hungarian - hu, Italian - it, Japanese - ja, Korean - kr, Latvian - la, Lithuanian - lt, Macedonian - mk, Dutch - nl, Polish - pl, Portuguese - pt, Romanian - ro, Russian - ru, Swedish - se, Slovak - sk, Slovenian - sl, Spanish - es, Turkish - tr, Ukrainian - ua, Vietnamese - vi, Chinese Simplified - zh_cn, Chinese Traditional - zh_tw.
- Other Properties: default: en; enum: ar, bg, ca, cz, de, el, en, fa, fi, fr, gl, hr, hu, it, ja, kr, la, lt, mk, nl, pl, pt, ro, ru, se, sk, sl, es, tr, ua, vi, zh_cn, zh_tw
MODE
- Name …: mode
- [Data type]: string
- Description…: Mode_. Example: html_. Determines the format of the response. Possible values are json, xml, and html. If the mode parameter is empty, the format is json by default.
- Other Properties: default: json; enum: json, xml, html
When you’re finished entering the parameters, Stoplight should look like this:
You don’t need to add security for this endpoint because you already configured global security in the previous section. However, if this endpoint had a unique security method, you could override the global security here by clicking the + Security button.
Step 4: Learn how to reuse parameters
The OpenAPI spec allows you to re-use parameters by storing the information in the components property. In the Stoplight editor, you reuse parameters by entering the parameter information in the Parameters section in the sidebar. (In the code behind the scenes, this is stored in components.)
To understand how this works, let’s re-use one of the query parameters.
To re-use a parameter:
- Right-click the Parameters folder in the lower-left corner of the sidebar and select New Query Parameter. (A parameter section similar to the query parameter sections appears.)
- Type lon and press enter.
- Populate the lon parameter here using the same information as before.
- Return to the previous query parameters section in the weather GET endpoint where you entered the lon parameter, and click the Reference button Reference button for this parameter.
- Search for “lon” and select it.
- When you link the parameter to the reference, the icon turns red.
- Switch to the Code editor and search for lon. You’ll now see a reference to a component:
- $ref: '#/components/parameters/lon'
You don’t need to do anything in the code here — this is just to point out what changed behind the scenes. You can use this same technique to re-use other parameters as well as other types of content, such as responses.
- Preview your updates by clicking the Preview button. If you select the /weather endpoint in the sidebar, the preview should look like this:
This endpoint in the OpenWeatherMap API doesn’t have any path, header, or body parameters, so you can skip those elements.
Step 5: Enter the responses and response schema information
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.
To enter the response information in Stoplight:
- Below the parameter section for the endpoint, click the + Response button. Then click the + Add Body button that appears within this expanded Response section.
- On the Schema tab, click Generate from JSON.
Here you’ll experience one of the coolest features in the Stoplight editor. The editor will automatically build out the response schema from a sample JSON response.
- Copy the sample response below.
{
"coord": {
"lon": -121.95,
"lat": 37.35
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04n"
}
],
"base": "stations",
"main": {
"temp": 45.25,
"feels_like": 41.16,
"temp_min": 41,
"temp_max": 50,
"pressure": 1026,
"humidity": 75
},
"visibility": 16093,
"wind": {
"speed": 2.57,
"deg": 36
},
"clouds": {
"all": 75
},
"dt": 1579415808,
"sys": {
"type": 1,
"id": 5845,
"country": "US",
"sunrise": 1579360793,
"sunset": 1579396557
},
"timezone": -28800,
"id": 0,
"name": "Santa Clara",
"cod": 200
}
- Paste the JSON you copied into the gray area where it says “Paste or write a JSON example below…” (Remove the empty curly braces first, and then paste in your sample.)
- Click Generate. Stoplight builds the schema for you!
- Add more detail about the response elements: click Description next to each property and add a description. Click Other Properties and add an example in the example field.
For the description and examples, copy over the information in the gray section below.
Sample descriptions and examples
coord >
- lon: description: City geolocation, longitude; example: 145.77
- lat: description: City geolocation, latitude; example: -16.92
weather >
- id: description: Weather condition id; example: 803
- main: description: Group of weather parameters (Rain, Snow, Extreme etc.); example: clouds
- description: description: Weather condition within the group; example: broken clouds
- icon: description: Weather icon id; example: 04n
- base: description: internal parameter; example: cmc stations
main >
- temp: description: Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit; example: 293.25
- feels_like: description: What the weather feels like despite the actual numbers; example: 41.16
- temp_min: description: Minimum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameters optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit; example: 289.82
- temp_max: description: Maximum temperature at the moment. This is deviation from current temp that is possible for large cities and megalopolises geographically expanded (use these parameters optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit; example: 295.37
- pressure: description: Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa; example: 1019
- humidity: description: ‘Humidity, %’; example: 83
- visibility: description: ‘Visibility, meter’; example: 16093
wind >
- speed: description: ‘Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.’; example: 5.1
- deg: description: ‘’; example: 150
clouds >
- all: description: ‘Cloudiness, %’; example: 75
- dt: description: ‘Time of data calculation, unix, UTC’; example: 1435658272
sys >
- type: description: Internal parameter; example: 1
- id: description: Internal parameter; example: 8166
- country: description: ‘Country code (GB, JP etc.)’; example: AU
- sunrise: description: ‘Sunrise time, unix, UTC’; example: 1435610796
- sunset: description: ‘Sunset time, unix, UTC’; example: 1435650870
- timezone: description: the timezone for the station; example: -28800
- id: description: City ID; example: 2172797
- name: description: Name; example: Cairns
- cod: description: Internal parameter; example: 200
- Now that you finished entering schema information, click the Preview button. The documentation should look like this:
Step 6: Preview, test, and publish the output
You’ve finished creating your OpenAPI spec, so let’s preview, test, and publish test the documentation:
- Click the Preview button in the upper-right corner.
- In the sidebar, select the /weather endpoint.
- Click the Try It tab near the top of the screen. (See note below – this feature won’t work now due to CORS restrictions with the API.)
- Enter your API key for the appid parameter. For details on getting the OpenWeatherMap API key, see Get an OpenWeatherMap API Key. (You can also type out the API key pictured in the image below. It’s not text because any API keys printed in text get exploited and then disabled by the vendor.)
- Enter your zip code for the zip parameter (for example, 98058). You might have to scroll to find the zip parameter as they are sorted alphabetically. The screen should look like this:
- If you try to click Send API Request, you should get an error that says “Network Error occurred.” That’s because of CORS issues (restrictions from the API and browser with making requests on a non-authorized domain). This will unfortunately prevent you from getting a response from the API request. You can, however, copy and paste the cURL request sample to your terminal and run it, and that should give you a response from the OpenWeatherMap API. (This assumes you have curl installed. On a Mac, it’s usually available by default.)
- At this point, you can either publish or export your API documentation. To publish, click the Publish button.
- Click on Back to workspace on the top-left to exit Stoplight. Look at the admin sidebar on the left. Click the Share button and choose the visibility settings for your documentation (it is set to Public by default). You can also invite other team members from the share dialog.
- You can export your OpenAPI spec file from Stoplight if you’d like to use it in other tools. From the published docs view, click the Export button and choose the type of code you want:
The Bundled References will resolve any $ref code and place them in the components section so there’s no duplication. The Original will export any $ref code, but not resolve them. The option you choose depends on what’s supported in the editor you’re bringing it to.
Tip: You can view the finished OpenWeatherMap API documentation from this tutorial on Stoplight here. If you got stuck in the tutorial somewhere along the way, you can click Export to download the OpenAPI description and paste it into your code.
We hope you found this guide helpful, and for similar content visit I’d Rather Be Writing or check out our other Stoplight guides. You can get started for free in Stoplight by clicking here.