Makrosites

Suas ideias em realidade digital!

Swagger/OpenAPI em PHP: documente sua API e facilite integrações

Swagger/OpenAPI em PHP: documente sua API e facilite integrações

Por que documentar sua API com Swagger/OpenAPI?

Quando você cria uma API em PHP, chega um ponto em que o maior problema deixa de ser “funcionar” e vira ser fácil de usar. A documentação com OpenAPI (Swagger) resolve isso.

Com Swagger/OpenAPI você consegue:


OpenAPI e Swagger: qual a diferença?


Estrutura mínima do OpenAPI (YAML)

Crie um arquivo openapi.yaml com este mínimo:

openapi: 3.0.3
info:
  title: Makrosites API
  version: "1.0.0"
  description: Documentação da API em PHP (exemplo prático)
servers:
  - url: https://www.makrosites.com.br/api
paths: {}

Esse arquivo já é válido, mas ainda não tem endpoints.


Documentando endpoints: exemplo real (GET /posts)

paths:
  /posts:
    get:
      summary: Listar posts
      description: Retorna a lista de posts ativos.
      tags: [Posts]
      responses:
        "200":
          description: Lista de posts
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Post"

Documentando endpoint com parâmetro (GET /posts/{id})

  /posts/{id}:
    get:
      summary: Buscar post por ID
      tags: [Posts]
      parameters:
        - in: path
          name: id
          required: true
          schema:
            type: integer
      responses:
        "200":
          description: Post encontrado
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Post"
        "404":
          description: Post não encontrado
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

Autenticação Bearer Token no Swagger (JWT)

Para rotas protegidas, você deve declarar um esquema de segurança:

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

E aplicar nas rotas:

  /posts:
    post:
      summary: Criar post
      tags: [Posts]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PostCreate"
      responses:
        "201":
          description: Criado com sucesso

Definindo schemas (models) reutilizáveis

components:
  schemas:
    Post:
      type: object
      properties:
        id: { type: integer, example: 10 }
        title: { type: string, example: "Meu post" }
        slug: { type: string, example: "meu-post" }
        created_at: { type: string, example: "2026-02-12 10:00:00" }

    PostCreate:
      type: object
      required: [title, slug]
      properties:
        title: { type: string, example: "Novo post" }
        slug: { type: string, example: "novo-post" }

    Error:
      type: object
      properties:
        error: { type: string, example: "Not Found" }
        details:
          type: array
          items: { type: string }

Arquivo OpenAPI completo (exemplo pronto)

Abaixo um exemplo enxuto e funcional (pode copiar e adaptar):

openapi: 3.0.3
info:
  title: Makrosites API
  version: "1.0.0"
  description: Documentação da API em PHP com exemplos (Posts + Auth)
servers:
  - url: https://www.makrosites.com.br/api

tags:
  - name: Auth
  - name: Posts

paths:
  /auth/login:
    post:
      summary: Login (retorna JWT)
      tags: [Auth]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [email, password]
              properties:
                email: { type: string, example: "admin@site.com" }
                password: { type: string, example: "123456" }
      responses:
        "200":
          description: Token gerado
          content:
            application/json:
              schema:
                type: object
                properties:
                  token: { type: string }
                  token_type: { type: string, example: "Bearer" }
                  expires_in: { type: integer, example: 900 }
        "401":
          description: Credenciais inválidas
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /posts:
    get:
      summary: Listar posts
      tags: [Posts]
      responses:
        "200":
          description: Lista de posts
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: "#/components/schemas/Post"

    post:
      summary: Criar post (protegido)
      tags: [Posts]
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PostCreate"
      responses:
        "201":
          description: Criado
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Post"

  /posts/{id}:
    get:
      summary: Buscar post por ID
      tags: [Posts]
      parameters:
        - in: path
          name: id
          required: true
          schema: { type: integer }
      responses:
        "200":
          description: Post
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Post"
        "404":
          description: Não encontrado
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

  schemas:
    Post:
      type: object
      properties:
        id: { type: integer, example: 10 }
        title: { type: string, example: "Meu post" }
        slug: { type: string, example: "meu-post" }
        created_at: { type: string, example: "2026-02-12 10:00:00" }

    PostCreate:
      type: object
      required: [title, slug]
      properties:
        title: { type: string, example: "Novo post" }
        slug: { type: string, example: "novo-post" }

    Error:
      type: object
      properties:
        error: { type: string, example: "Erro" }
        details:
          type: array
          items: { type: string }

Como publicar o Swagger UI no seu servidor

Você tem duas formas fáceis:

Opção 1) Pasta /docs com Swagger UI (simples)

Exemplo (no initializer):

url: "https://www.makrosites.com.br/docs/openapi.yaml"

Opção 2) Swagger UI via CDN (bem leve)

Crie um docs/index.html que carrega via CDN e aponta para seu arquivo OpenAPI.


Boas práticas para OpenAPI