Sequence Diagrams for API Flows: REST, Auth, and Microservices Examples
- Copy-paste sequence diagram code for common API patterns: REST CRUD, JWT auth, OAuth, webhooks
- Microservices communication patterns with async messaging
- Free browser tool renders diagrams instantly from text
- Export as PNG or SVG for API documentation
Table of Contents
A sequence diagram is the fastest way to explain how an API call actually works. Instead of writing three paragraphs about "the client sends a request to the server, which validates the token, then queries the database..." you draw it in five lines of text and everyone gets it immediately. This guide gives you copy-paste sequence diagram code for the most common API patterns: REST endpoints, JWT authentication, OAuth flows, webhooks, and microservice choreography.
Every example below works in our free sequence diagram tool. Paste the code, see the diagram, export as PNG for your README or SVG for your wiki.
REST API: Request-Response Flow
The standard REST pattern is the foundation of most API documentation. Here is a complete CRUD cycle for a user resource:
sequenceDiagram
actor Developer
participant API as REST API
participant DB as Database
Developer->>API: POST /users (name, email)
API->>DB: INSERT INTO users
DB-->>API: User record (id: 42)
API-->>Developer: 201 Created {id: 42}
Developer->>API: GET /users/42
API->>DB: SELECT * FROM users WHERE id=42
DB-->>API: User record
API-->>Developer: 200 OK {user data}
Notice how the diagram immediately shows the full round-trip. A new developer joining your team can look at this and understand the data flow without reading a single line of application code.
For error handling, use the alt block to show both success and failure paths:
sequenceDiagram
participant Client
participant API
participant DB
Client->>API: GET /users/999
API->>DB: SELECT WHERE id=999
alt User found
DB-->>API: User record
API-->>Client: 200 OK
else Not found
DB-->>API: null
API-->>Client: 404 Not Found
end
This is cleaner than documenting error responses in a table somewhere. The diagram shows when and why each response code occurs. If you are building developer flowcharts alongside your API docs, sequence diagrams handle the temporal flow while flowcharts handle decision logic.
JWT Authentication: Login, Token Validation, Refresh
JWT auth involves multiple steps that confuse developers new to the pattern. A sequence diagram makes the token lifecycle crystal clear:
sequenceDiagram
actor User
participant App as Frontend
participant Auth as Auth Service
participant API
User->>App: Enter email + password
App->>Auth: POST /auth/login
Auth->>Auth: Validate credentials
alt Valid
Auth-->>App: 200 {accessToken, refreshToken}
App->>App: Store tokens
App->>API: GET /data (Bearer token)
API->>API: Verify JWT signature
API-->>App: 200 Protected data
else Invalid
Auth-->>App: 401 Unauthorized
App-->>User: Show error
end
The self-call arrows (Auth->>Auth: Validate credentials) are important here. They show that validation happens internally on the auth service, not as a separate network call. This distinction matters for understanding latency and debugging.
For token refresh, add a separate flow showing what happens when the access token expires:
sequenceDiagram
participant App
participant API
participant Auth
App->>API: GET /data (expired token)
API-->>App: 401 Token expired
App->>Auth: POST /auth/refresh (refreshToken)
Auth-->>App: 200 {newAccessToken}
App->>API: GET /data (new token)
API-->>App: 200 Data
Paste either of these into the sequence diagram maker and you have documentation-ready visuals in seconds.
OAuth 2.0: The Full Authorization Code Flow
OAuth is the flow that generates the most confused questions in developer forums. A sequence diagram cuts through the confusion:
sequenceDiagram
actor User
participant App
participant AuthServer as Auth Provider
participant API as Resource Server
User->>App: Click "Login with Google"
App->>AuthServer: Redirect to /authorize
AuthServer->>User: Show consent screen
User->>AuthServer: Grant permission
AuthServer-->>App: Redirect with auth code
App->>AuthServer: POST /token (code + secret)
AuthServer-->>App: Access token + refresh token
App->>API: GET /user/profile (Bearer token)
API-->>App: User profile data
App-->>User: Logged in, show dashboard
The key insight that a sequence diagram captures: the auth code goes from the browser back to your server, then your server exchanges it for tokens. That two-step exchange is what makes OAuth secure, and it is almost impossible to explain in prose without a diagram.
This same pattern applies to GitHub, Facebook, Apple, and any other OAuth 2.0 provider. Change the participant names and you have documentation for whatever auth integration you are building.
Sell Custom Apparel — We Handle Printing & Free ShippingMicroservices: Sync, Async, and Event-Driven Patterns
Microservices communicate through a mix of synchronous HTTP calls and asynchronous message queues. Sequence diagrams handle both:
sequenceDiagram
participant Gateway as API Gateway
participant Orders
participant Inventory
participant Payment
participant Queue as Message Queue
Gateway->>Orders: POST /orders
Orders->>Inventory: Check stock (sync)
Inventory-->>Orders: In stock
par Process payment and reserve
Orders->>Payment: Charge card
Payment-->>Orders: Payment confirmed
and
Orders->>Inventory: Reserve items
Inventory-->>Orders: Reserved
end
Orders->>Queue: Publish OrderCreated event
Note over Queue: Async subscribers
Queue->>Inventory: Update stock count
Queue->>Gateway: Send confirmation email
The par block shows payment and inventory reservation happening simultaneously. The message queue section shows the async event-driven part. Combining both patterns in one diagram gives your team a complete picture of a single order flow.
For saga patterns (where you need compensating transactions on failure), nest an alt inside the flow to show the rollback path. This gets complex fast in prose but stays readable in a diagram.
If your architecture uses more than five or six services in a single flow, consider breaking it into multiple focused diagrams rather than one giant one. Each diagram should tell the story of one use case. For the overall system structure, an ER diagram or class diagram might complement the sequence view.
Webhooks: Documenting Async Callbacks
Webhooks flip the usual request-response pattern. Your service registers a URL, and a third-party service calls it later when something happens. A sequence diagram makes the timing explicit:
sequenceDiagram
participant App as Your App
participant Stripe
participant DB as Database
App->>Stripe: Create checkout session
Stripe-->>App: Session URL
App-->>App: Redirect user to Stripe
Note over Stripe: User completes payment
Note over Stripe: Minutes or hours later...
Stripe->>App: POST /webhooks/stripe
App->>App: Verify signature
App->>DB: Update order status
App-->>Stripe: 200 OK
The Note over lines are critical here. They show the time gap between the initial request and the callback. Without them, someone reading the diagram might think the webhook fires immediately.
This pattern applies to payment processors (Stripe, Square), email services (SendGrid, Mailgun), CI/CD pipelines (GitHub Actions), and any system where you register a callback URL.
For polling patterns (where you repeatedly check instead of receiving a callback), use a loop block:
loop Every 5 seconds
App->>API: GET /job/123/status
alt Complete
API-->>App: {status: "done", result: ...}
else Still processing
API-->>App: {status: "pending"}
end
end
Best Practices for API Sequence Diagrams
After creating hundreds of API sequence diagrams, here is what works:
- One diagram per use case. "User creates an order" is one diagram. "User creates an order, then cancels it, then requests a refund" is three diagrams. Keep each one focused.
- Name participants by role, not by technology. Use "Auth Service" instead of "Keycloak." Use "Database" instead of "PostgreSQL." Technology choices change; roles do not.
- Show the happy path first. Create one diagram with the successful flow, then create a second one for error handling. Cramming both into one diagram makes it unreadable.
- Use activation bars for long operations. If the database query takes noticeable time, the activation bar on the Database lifeline communicates that visually.
- Include HTTP methods and status codes.
POST /ordersand200 OKare more useful than "Send request" and "Get response."
Version your diagrams alongside your code. Since these are plain text, they fit naturally in a Git repository. A Mermaid file in your /docs folder renders directly in GitHub and GitLab README files. For teams using VS Code, the Mermaid preview extension shows diagrams inline as you edit.
For diagrams that show system structure rather than message flow, an ER diagram maps your data model, while a flowchart maps decision logic. Use sequence diagrams specifically when the order of messages matters.
Paste Your API Flow and See It Instantly
Copy any example from this guide into the editor. Renders in your browser, exports as PNG or SVG, no signup needed.
Open Free Sequence Diagram MakerFrequently Asked Questions
How do I create a sequence diagram for a REST API?
Define participants (Client, API, Database), then write messages with HTTP methods: Client->>API: GET /users. Use alt blocks for success vs error responses, and dashed arrows (-->>) for return values. Our free tool renders the diagram from text instantly.
What is the best tool for API sequence diagrams?
For quick diagrams that live in documentation, text-based tools are fastest. You type the flow in code, the diagram renders automatically, and the source fits in version control. Our free browser tool uses Mermaid syntax and exports PNG or SVG with no signup.
How do I show async operations in a sequence diagram?
Use dashed open arrows for async fire-and-forget messages. For parallel operations, wrap them in a par block. For webhooks and callbacks, add Note annotations to indicate the time gap between the initial request and the callback.
Can I use sequence diagrams in API documentation tools like Swagger?
Swagger and OpenAPI handle endpoint-level documentation. Sequence diagrams complement them by showing multi-endpoint flows. You can embed exported PNG or SVG images in your API docs, or use Mermaid syntax directly in GitHub-hosted documentation.

