How to Create API Specifications with ChatGPT (with examples)

As a technical writer, ChatGPT offers an opportunity to streamline the API documentation process. Let’s dive into how to harness ChatGPT’s capabilities to create a ready-to-use Open API aka Swagger spec template.

This guide is designed to benefit both newcomers to ChatGPT and experienced technical writers, to help you accelerate tech document creation and explore some of ChatGPT’s capabilities.

REST API TEMPLATE – Download this 28-page MS Word template to document your REST/Web APIs. This template pack includes detailed examples, guidelines, and screenshots.
Full details here: REST API Template (MS Word)

In upcoming tutorials, we’ll explore more API documentation processes, including creation, testing, and publication, with ChatGPT as our co-pilot.

ChatGPT Prompt Workflow

Here’s a suggested workflow to get the most from ChatGPT, especially if you’re working with technical materials.

  • Create a single chat – instead of create multiple chats, each with different prompts, gather all your prompts into a single chat. The continuity between the prompts in a single chat seems to lead to higher quality responses. It also makes it easier to organize your chats in the side bar.
  • Identify the high level goals – by doing so, ChatGPT isn’t starting cold. This gives it the context it needs to provide more accurate, less generic responses.
  • Provide sample material – again, this gives it a frame of reference. For example, if you want it to respond in a particular voice or writing style, drop in some articles of the author you have in mind.
  • Ask for a specific result, such as the Open API spec in YAML format. Ask it to restrict the response to a certain number of words, if you find it’s too verbose.
  • Remind ChatGPT to check/validate the accuracy of its results. If it find errors – and it will – it can regenerate the response. Ask it to apply Track Changes and identify the edits it made. Don’t take anything for granted.
  • Ask it to combine the previous responses in a single response. This makes it easy to export the material. However, do check that it hasn’t overlooked any of its own responses.
  • Convert the final response into markdown, HTML, or CSV depending on your needs.
  • Finally, proof the text in MS Word as it often catches rogue typos.

Put your goal in context for ChatGPT

When using ChatGPT, I typically start by stating my high level goal, then drilling down to more granular tasks. This seems to put things in context for ChatGPT and leads to more detailed, less generic, responses.

Here’s the sample prompt I used:

As a technical writer, I want to create API Specs with ChatGPT. Provide me with a set of instructions on how to this.

I’ve distilled its response but here are the main points.

    1. Understand the API: Before you begin, ensure you have a clear understanding of the API you’re documenting. Familiarize yourself with its endpoints, request and response formats, authentication methods, and any other relevant details.
    2. Gather Information: Collect all the necessary information about the API, including endpoint URLs, HTTP methods, request parameters, response formats, and any specific requirements for authentication or authorization.
    3. Define the API Structure:
      • Start by defining the basic structure of your API documentation. This typically includes an introduction, overview, and sections for each endpoint.
      • Decide on a consistent format for documenting each endpoint, such as using tables or structured text.
    4. Use ChatGPT for Descriptions:
      • For each endpoint, use ChatGPT to generate detailed descriptions.
      • Provide a brief summary of what the endpoint does.
      • Use ChatGPT to generate explanations of request parameters, including their data types, required fields, and any constraints.
      • Similarly, use ChatGPT to describe the response format, including data types, possible status codes, and example responses.
    5. Include Example Requests and Responses:
      • Request and response examples are crucial for understanding how the API works. Use ChatGPT to generate example requests and responses for each endpoint.
      • Ensure that the examples cover various scenarios, including successful and error responses.
    6. Document Authentication and Authorization:
      • Describe the authentication methods required to access the API. This may include API keys, OAuth tokens, or other authentication mechanisms.
      • Provide step-by-step instructions, if necessary, on how to obtain and use authentication credentials.
    7. Document Error Handling:
      • Explain how the API handles errors, including common error codes and their meanings.
      • Use ChatGPT to generate descriptions of potential error scenarios and how to handle them.
    8. Add Visuals and Diagrams:
      • Visual aids like diagrams, flowcharts, or sequence diagrams can enhance the clarity of your API documentation. Use ChatGPT to generate descriptions for these visuals.
    9. Review and Edit:
      • After using ChatGPT to generate content, review and edit it for accuracy, consistency, and clarity.
      • Ensure that the generated content aligns with your company’s style and formatting guidelines.
    10. Organize and Format:
      • Organize the API documentation logically, with clear headings and sections for each endpoint.
      • Format the documentation for readability, using consistent fonts, colors, and styles.
    11. Include Cross-References and Links:
      • If you have related API documentation, cross-reference it appropriately.
      • Include links to relevant external resources, such as API reference guides or support documentation.
    12. Version Control:
      • Store your API specs in a version-controlled repository (e.g., Git) to track changes and collaborate with your team.
    13. Quality Assurance:
      • Test the API based on your documentation to ensure accuracy.
      • Gather feedback from developers and stakeholders to improve the documentation.
    14. Maintenance:
      • Keep your API specs up-to-date as the API evolves. Update the documentation whenever there are changes or additions to the API.
    15. Publish and Share:
      • Publish the API documentation on your company’s website or documentation portal.
      • Share it with developers, customers, and other stakeholders who need access to the API.

Finally, it includes the following caveat. “Using ChatGPT as a writing assistant can significantly speed up the documentation process and help you create comprehensive API specs. However, it’s essential to review and edit the generated content to ensure accuracy and clarity.”

How to create an API Specification template

As mentioned earlier, I typically ‘orient’ ChatGPT by asking high-level questions first, then drilling down it the details. You don’t have to do this. If you want to create something as simple as an Open API spec, you can go straight to the prompt.

In ChatGPT, instead of creating multiple chats for each question, I use a single chat for specific tasks, and spoon-feed questions to get more detailed responses. In the following articles, we’ll look into this in more details.

The next step is to ask ChatGPT to create the Open API spec.

Its response is to walk me through the process of creating a Swagger/OpenAPI specification template.

If you’re an experience technical writer, you probably know most of the already. However, for novice writers, this can be quite helpful.

Prompt:

How to create a Swagger Open API spec template with ChatGPT

ChatGPT response:

Creating a Swagger/OpenAPI specification template is a structured process, and I’ll provide you with a detailed explanation on how to do it. Swagger/OpenAPI is a powerful tool for defining, documenting, and testing APIs. Here’s a step-by-step guide:

Understand Your API: Before you start creating the OpenAPI spec, you need a clear understanding of the API you want to document. Know its endpoints, request and response formats, authentication methods, and any other relevant details.

Choose a Format: Swagger/OpenAPI supports both JSON and YAML formats. You can choose either based on your preference. YAML is often preferred for its readability.

Start with Basic Information:

Begin your OpenAPI document by specifying the version, title, and description of your API.

You can also provide contact information and license details if necessary.

Example:

openapi: 3.0.0
info:
  title: Your API Title  
  description: A brief description of your API.
  version: 1.0.0
  contact:  
    name: Your Name
    email: [email protected]
  license:
    name: Your License
    url: https://yourlicenseurl.com 

Define Servers:

Specify the servers where your API is hosted. This can include different environments such as development, staging, and production.

Example:

servers:
  - url: https://api.example.com/v1

Define Paths and Operations:

Document each API endpoint by specifying its path, HTTP method, and a summary description.

Include request and response parameters, schemas, and examples.

Example:

paths:
  /users:
    get:
      summary: Get a list of users
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

Define Components:

Use the components section to define reusable components like schemas, security schemes, and response objects.

Example:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        username:
          type: string
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

Security Definitions:

If your API requires authentication, define security schemes and apply them to relevant endpoints.

Example:

security:
  - BearerAuth: []  

Testing and Validation:

Before finalizing your OpenAPI spec, validate it using tools like the Swagger Editor or online validators to ensure it’s correctly formatted.

Documentation:

Generate documentation from your OpenAPI spec using tools like Swagger UI or ReDoc. These tools automatically create interactive documentation for your API.

Version Control:

Store your OpenAPI spec in a version-controlled repository (e.g., Git) to track changes and collaborate with your team.

Keep it Updated:

As your API evolves, make sure to keep your OpenAPI spec up-to-date to reflect any changes.

Remember to adapt the above steps to your specific API requirements. OpenAPI is a versatile tool that allows you to document APIs comprehensively. Following these steps should help you create a useful Swagger/OpenAPI specification for your project.

Create a Swagger Open API Specification template in JSON format

You now have a few options.

First, I asked for the template in JSON format.

CHATGPT Prompt

Create a Swagger Open API spec template in JSON format

ChatGPT

{
  "openapi": "3.0.0",
  "info": {
    "title": "Your API Title",
    "description": "A brief description of your API.",
    "version": "1.0.0",
    "contact": {
      "name": "Your Name",
      "email": "[email protected]"
    },
    "license": {
      "name": "Your License",
      "url": "https://yourlicenseurl.com"
    }
  },
  "servers": [
    {
      "url": "https://api.example.com/v1"
    }
  ],
  "paths": {
    "/users": {
      "get": {
        "summary": "Get a list of users",
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/User"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "User": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer"
          },
          "username": {
            "type": "string"
          }
        }
      }
    },
    "securitySchemes": {
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "JWT"
      }
    }
  },
  "security": [
    {
      "BearerAuth": []
    }
  ]
}

Create a Swagger Open API Specification template in YAML format

Next, I asked for the template in YAML format.

CHATGPT Prompt

Here’s a basic Swagger/OpenAPI spec template in YAML format:

openapi: 3.0.0
info:
  title: Your API Title
  description: A brief description of your API.
  version: 1.0.0
  contact:
    name: Your Name
    email: [email protected]
  license:
    name: Your License
    url: https://yourlicenseurl.com
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: Get a list of users
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        username:
          type: string
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
security:
  - BearerAuth: []

This YAML template provides a basic structure for a Swagger/OpenAPI specification. You can customize it further to match the specific details and endpoints of your API. Replace the placeholders (e.g., “Your API Title,” “Your Name,” etc.) with your actual API information and definitions.

Summary

Using ChatGPT as a technical writing assistant can significantly expedite the documentation process. However, as mentioned, it’s crucial to review and edit the generated content to ensure accuracy and clarity.

Finally, I’d recommend to develop a workflow to get the most from ChatGPT, such as creating a single chat for continuity, and to compare ChatGPT against Claude and Google Bard to see which gives the best results with your tech document requirements.

REST API TEMPLATE – Download this 28-page MS Word template to document your REST/Web APIs. This template pack includes detailed examples, guidelines, and screenshots.
Full details here: REST API Template (MS Word)