OpenAPI definitions, formerly known as Swagger files, allow developers to specify the operations and metadata of their APIs in machine-readable form. This enables them to automate various processes around the API lifecycle.
We’ve already covered 5 reasons you should use OpenAPI/Swagger for your APIs on this blog. If you are convinced now that OpenAPI is something you want to get your hands dirty with, you have come to the right place!
OpenAPI definitions are simple JSON or YAML files that you can create and edit with any text editor. But the right tooling can make your job a lot easier. In this article, we would like to showcase one of tools for the API design stage, the Swagger Editor, and be your step-by-step guide for creating your first OpenAPI definition.
When you first open the editor it shows the Swagger Petstore API, which is a sample API used by the Swagger project to show off the extensive capabilities of the OpenAPI specification. We’ll replace it with something simpler in a minute, but first, let‘s have a look around the editor.
As you can see, the editor features a split view; the left side contains the specification in YAML serialization and the right side shows generated interactive API documentation. Any edits made on the left side momentarily reflect on the right side.
OpenAPI definitions can be serialized in either YAML or JSON and even though Swagger Editor understands both, it is not shy to communicate its preference for YAML: when you copy and paste JSON it asks you to convert it.
A top bar above the split view contains the following menu:
- Under File, you can import an existing OpenAPI file either by uploading it from your computer or reading it from a remote URL. You can also download YAML and JSON versions of your definition or clear the editor.
- Under Edit, you currently have just one option, which is to convert JSON into YAML.
- The Generate Server and Generate Client menus list a variety of typical programming languages and frameworks. If you click on one of them you’ll be prompted with a ZIP file download which contains a skeleton project for producing or consuming an API with your definition.
The Generate Server and Generate Client features are built on the open source Swagger Codegen project, or specifically, its hosted version at generator.swagger.io. This means that, unlike the rest of the application, if you use these features your OpenAPI definition will be sent to that server for processing.
It should be noted that Swagger Editor is a tool to help you learn writing OpenAPI and work directly with machine-readable API definitions. While the editor assists you with standard IDE features such as syntax highlighting, auto-completion and immediate validation, it is not a visual API designer or application targeted at non-developers. You can only edit on the left side.
Create an OpenAPI Definition
If you are an OpenAPI beginner, the Swagger Petstore API might feel a little overwhelming at first. So, let’s clear the editor (File → Clear editor) and start with a blank slate. For the purpose of this article, I’m using ipify, a simple API that allows software clients to determine their public IP address even behind a NAT. This API is a great example for testing because it is very simple, and also allows unlimited access without an API key. You are free to test with this API or, if you already have your own API, start building the definition for that.
Copy the following lines into the editor.
swagger: '2.0' info: description: A Simple IP Address API title: ipify version: v1
The first line indicates the type and version of the specification. Using "info," you can set basic human-readable information such as title, description, and version.
Check out the right side of the editor now. Your title, version, and description have been formatted. You also see a red box titled Errors. Parser errors, for example, if you have malformed YAML, are shown both in this box and also with a red X on the respective line. Schema errors, such as the missing paths property, are shown only in this box. Whenever you see the red box you know that there is something to fix in your definition. You should only generate code or save your definition and import it into another tool when the red error box has disappeared.
Continue with the information about the API endpoint’s base URL:
host: api.ipify.org schemes: - https basePath: /
Not much has changed on the right side, and we still have the paths error, so let’s fix that by adding an operation to our API:
paths: /: get: summary: Get client IP responses: '200': description: Success response
So what have we done now? We’ve added a single path at the root and an operation with the HTTP GET verb. The summary, which is basically the name of the operation, is set to “Get client IP,” and there’s one possible response defined for the 200 status code under responses. This is the bare minimum to have an operation listed in the documentation on the right side and the error box disappear. You can already try the operation by clicking the Try it out button inside the operation’s box first (if you don’t see this box it might be collapsed, click on the operation’s name to open it), and then Execute. The request is executed from your browser directly to the API and the response is shown. Note that this requires the API to support CORS (cross-origin resource sharing), which ipify does.
API operations typically require parameters. While ipify works without parameters, they do support a parameter to modify the response format. Let’s add this parameter! Here’s the extended snippet for the paths section:
paths: /: get: summary: Get client IP parameters: - in: query name: format type: string description: 'The format to return the response in, i.e. json.' default: json responses: '200': description: Success response
As you can see, parameters use in to declare where they are added to the request. In this example, it’s a query parameter. It is possible to specify the name and type and also add a description and default value. If you look at the generated API documentation now you can see the list of parameters. Each parameter contains an editable text field so you can test your API operation with different inputs.
Finally, let’s add a description of the response, so the readers of our documentation can expect what the output of the API will be even before sending their request. Once again, here goes the full snippet for the paths section:
paths: /: get: summary: Get client IP parameters: - in: query name: format type: string description: 'The format to return the response in, i.e. json.' default: json responses: '200': description: Success response schema: type: object properties: ip: type: string example: 22.214.171.124
As you can see, I’ve added a schema property to the response. The response type is given as an object with a string-typed property called ip and an example value. In the generated API documentation, you can toggle between viewing this example or a description of the model for the response. Note that the OpenAPI specification relies on another specification called JSON Schema for modeling JSON objects for requests and responses.
If you’ve followed the tutorial up to here, congratulations, you now have created your first OpenAPI file and observed how such a machine-readable definition can easily and automagically turn into interactive API documentation. Feel free to play around with it. You could import some examples from the web or go back to the Swagger Petstore example by clearing the editor and then refreshing the page.
Did you know that BlazeMeter allows you to create functional and load tests for APIs based on an OpenAPI specification file, so why not try this with the API you just created? Go to File, DownloadJSON and store swagger.json to your computer. Sign in to BlazeMeter, click CreateTest, APITestMaker, Swagger and upload the previously downloaded file. Once you click GenerateTests, the API Test Maker will show your API endpoints in a view not unlike Swagger Editor and automatically generates test cases that you can run easily.
Is Swagger Editor the right tool for you? It depends. It is great to learn OpenAPI if you want to dive into the specification, and it is also very minimalist, which makes it quick to learn. If you need some more hand-holding or look for cloud and collaboration features you should probably use a more advanced tool. Both open source and commercial offerings are available and we will take a look at some of them in future articles on this blog.