Skip to main content
RESTful Principles
CHAPTER 26 Beginner

API Documentation with Swagger/OpenAPI

Updated: May 13, 2026
5 min read

# CHAPTER 26

API Documentation with Swagger/OpenAPI

1. Introduction

If you build a flawless API but don't tell anyone how to use it, it is entirely useless. Frontend developers need to know exact URLs, required headers, JSON payload formats, and status codes. Writing this manually in a Word document is tedious and quickly becomes outdated. In Chapter 26, we will introduce the OpenAPI Specification (formerly Swagger), the absolute industry standard for documenting REST APIs.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain what the OpenAPI Specification is.
  • Understand the relationship between OpenAPI and Swagger.
  • Read and write a basic openapi.yaml file.
  • Describe how interactive documentation works.
  • Understand the value of auto-generated documentation.

3. Beginner-Friendly Explanation

Imagine buying a complex piece of IKEA furniture. You need a manual that shows exactly what screws go where. An API Documentation is the manual for your API. OpenAPI is a standardized language for writing that manual. Instead of writing it in English, you write it in a structured format (YAML or JSON). Swagger UI takes that structured YAML file and magically turns it into a beautiful, interactive webpage. Developers can actually press buttons on the webpage to test your API directly from the documentation!

4. Real-World Examples

  • Stripe / Twilio: These companies are famous for their world-class API documentation. They use OpenAPI specs behind the scenes to generate SDKs and interactive web pages.
  • Swagger UI: Look up "Swagger Petstore". It is a live example of an interactive documentation page generated purely from an OpenAPI file.

5. Detailed Code Examples

Here is an example of what an openapi.yaml file looks like for a simple /users endpoint.
yaml
123456789101112131415161718192021222324252627282930313233343536
openapi: 3.0.0
info:
  title: My PHP REST API
  version: 1.0.0
  description: A simple API for managing users.

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

paths:
  /users:
    get:
      summary: Retrieve a list of users
      description: Fetches a paginated list of all active users.
      parameters:
        - in: query
          name: page
          schema:
            type: integer
          description: The page number to fetch
      responses:
        '200':
          description: A JSON array of user objects
          content:
            application/json:
              schema:
                type: array
                items:
                  type: object
                  properties:
                    id:
                      type: integer
                    name:
                      type: string
        '401':
          description: Unauthorized. Missing or invalid Bearer token.

6. Request/Response Examples

When developers visit your Swagger UI page, they see the GET /users endpoint. They can click a "Try it out" button, type 2 into the page parameter box, and hit execute. The Swagger UI will construct the URL (https://api.mywebsite.com/v1/users?page=2) and make the HTTP request for them!

7. HTTP Examples

The OpenAPI file strictly defines what HTTP methods are allowed for each path. Under /users, we define get:. We could also define post: under the exact same path to document how to create a user.

8. JSON Examples

OpenAPI strongly encourages defining reusable "Schemas". If you define a User schema once, you can reference it in GET responses, POST payloads, and PUT payloads without rewriting it.
yaml
123456789101112131415161718
components:
  schemas:
    User:
      type: object
      required:
        - name
        - email
      properties:
        id:
          type: integer
          readOnly: true
        name:
          type: string
          example: "Jane Doe"
        email:
          type: string
          format: email
          example: "jane@example.com"

9. Best Practices

  • Design-First API Development: Write your OpenAPI .yaml file *before* you write any PHP code. This allows you to plan the exact JSON structures and share them with the frontend team so they can start working immediately using mock servers.
  • Use Annotations in PHP: Writing massive YAML files by hand is hard. Advanced PHP developers use tools like zircote/swagger-php. You write specially formatted comments directly above your PHP controller functions, and the tool automatically generates the openapi.json file for you!

10. Common Mistakes

  • Outdated Documentation: Writing a manual Word document and forgetting to update it when you change the API is the #1 complaint of frontend developers. Using OpenAPI (especially via PHP code annotations) ensures your documentation is always perfectly synced with your code.

11. Mini Exercises

  1. 1. Search Google for "Swagger Petstore". Open the link.
  1. 2. Click on the GET /pet/{petId} row.
  1. 3. Click "Try it out". Enter an ID (like 1 or 2). Click "Execute" and view the real API response right in the browser.

12. Coding Challenges

Challenge 1: Look at the YAML example in Section 5. Add a 404 response definition under the responses: block, describing what happens if the URL is not found.

13. MCQs with Answers

Question 1

What is the industry standard specification for defining REST APIs?

Question 2

What does Swagger UI do?

Question 3

Why is "Design-First" API development beneficial?

14. Interview Questions

  • Q: Explain the relationship between OpenAPI and Swagger.
  • Q: Why is an interactive documentation tool like Swagger UI superior to a standard PDF manual?
  • Q: Describe how using code annotations (like swagger-php) solves the problem of outdated documentation.

15. FAQs

Q: I heard about Postman. Is that the same as Swagger? A: They are closely related but serve different primary purposes. Postman is primarily a tool for *testing* APIs (which we cover in the next chapter). Swagger/OpenAPI is primarily for *documenting* them. However, you can import an OpenAPI file directly into Postman!

16. Summary

In Chapter 26, we learned that excellent APIs require excellent documentation. The OpenAPI Specification allows us to describe our URLs, headers, payloads, and status codes in a standardized YAML format. Tools like Swagger UI then convert that specification into a beautiful, interactive webpage where developers can read about and test our API effortlessly.

17. Next Chapter Recommendation

Now that our API is documented, we need a way to aggressively test it during development. Proceed to Chapter 27: Testing REST APIs with Postman to master the ultimate API developer tool.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·