How to write a basic OpenAPI schema

Creating an OpenAPI schema can seem daunting for those new to API design. However, it’s a powerful way to describe and document your REST APIs. OpenAPI, formerly known as Swagger, has become the standard language for API specifications. In this article, we’ll cover what an OpenAPI schema is, why it’s useful, and how to write one from scratch. Our focus will be on OpenAPI 3.0, the latest version of this specification.

By the end of this read, you’ll be able to craft a basic OpenAPI schema that outlines the capabilities of your API, ready for both human comprehension and technological interaction.

What is an OpenAPI Schema?

An OpenAPI schema is a document that describes the entire interface of your REST API. It is written in either YAML or JSON, with YAML being the preferred choice for its readability. This schema includes information about endpoints, the data they accept and return, and the operations that can be performed through your API.

Why Use OpenAPI?

OpenAPI offers a standard, language-agnostic way to describe RESTful APIs. This facilitates clear communication between front and back-end teams, streamlines the development process, and makes integrating third-party services easier. Moreover, tools can interpret OpenAPI documents, assisting with automatic code generation, documentation production, and test case development.

Let’s break down the process of writing a basic OpenAPI schema into manageable steps.

Setting up Your Environment

Before you embark on writing your first OpenAPI schema, it’s beneficial to set up an environment that will make the process smoother. For beginners, using an online editor like SwaggerHub can be a great way to get started with real-time feedback and a visual representation of your API structure.

Basic Structure of an OpenAPI Definition

An OpenAPI document primarily consists of two parts: the overarching structure that includes the openapi version and the info object, and the paths object that contains the details of the API’s endpoints.

OpenAPI Object: The Root

openapi: 3.0.0
info:
  title: Sample API
  description: A sample API to illustrate OpenAPI concepts
  version: 0.1.0
servers:
  - url: 'https://api.sample.com/v1'

The above fragment specifies which version of OpenAPI you’re using (3.0.0), provides basic information about your API, and sets the server URL which serves as the API’s base path for the endpoints defined later.

Info Object: API Metadata

The info object houses the core metadata about your API:

  • title: The display name of your API.
  • description: A short description of the API. You can use Markdown for formatting here.
  • version: The version of the API specification itself.

Servers Object: Host and Base Path

In the servers array, you define one or multiple server objects. Each contains a url that is the base path for your API endpoints.

Defining API Endpoints: The Paths

The paths object is where you start detailing your API’s operations. Each path represents an endpoint, and each endpoint can support multiple operations like GET, POST, etc.

paths:
  /artists:
    get:
      summary: Returns a list of artists
      responses:
        '200':
          description: A JSON array of artist names

Here we have a GET operation on the /artists endpoint, with an expected successful response code 200.

Parameters: Defining Variables

Parameters in OpenAPI cover details like where the parameter is expected (path, query, header, or cookie), it’s data type, and whether it’s required or has a default value.

parameters:
  - in: query
    name: genre
    schema:
      type: string
    required: false

Above, we’ve described an optional genre query parameter of the type string.

The Request Body: Input Data

When defining operations that can accept input data, like POST, PUT, or PATCH, you’ll use the requestBody field:

requestBody:
  required: true
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/Artist'

This snippet references a component schema for an artist, specifying JSON data is expected in the request body.

Responses: What to Expect

The responses object details what clients can expect as a response after making a request. You define the possible HTTP status codes and the structure of the response data.

responses:
  '200':
    description: A list of artists
    content:
      application/json:
        schema:
          type: array
          items:
            $ref: '#/components/schemas/Artist'

Above, we’ve detailed a successful 200 response, returning a JSON array of artists.

Components: Reusable Definitions

To avoid repetition, OpenAPI allows for the definition of reusable components.

components:
  schemas:
    Artist:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

Now, this Artist schema can be referred elsewhere in your API definition.

Tying it Together: Authentication and Security

For APIs requiring authentication, OpenAPI lets you define security schemes under the components object. Then, you can reference these schemes in the global security field or under specific operations.

Wrapping Up: The Final Schema

By following the structured approach above, you can progressively build out a complete OpenAPI schema that captures the essence of your API.

Remember, this walkthrough covers the fundamentals of OpenAPI schema writing. As you get more comfortable, you’ll likely utilize more advanced features of OpenAPI to capture the full breadth and depth of your API’s capabilities.

Are you ready to put this knowledge into practice? Get your hands on your keyboard and start drafting that schema. As you do, consider exploring tools like Swagger to streamline your process further. If you have questions or want to delve deeper, seek out the full OpenAPI 3.0 Specification on GitHub.