Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

API Documentation with Redoc and Swagger UI

By Kokil Thapa | Last reviewed: August 2026

Shipping a REST API without clear documentation guarantees integration failures, support tickets, and wasted developer time. Effective API documentation with Redoc and Swagger UI transforms a raw OpenAPI specification into an interactive reference that frontend teams, mobile developers, and third-party partners can actually use. This guide covers practical implementation in Laravel 12, compares both renderers honestly, and shows you how to automate spec generation so your docs never drift from your code.

How Do You Generate OpenAPI Specs for API Documentation with Redoc and Swagger UI?

Before you can render anything, you need a valid OpenAPI 3.0+ specification. Writing YAML by hand is unsustainable for any API beyond trivial size. In the Laravel ecosystem, two packages dominate automated spec generation in 2026: Laravel API best practices increasingly favour code-first approaches where documentation lives alongside your route definitions and form requests.

Scramble (dedoc/scramble) analyses your actual PHP code — routes, controllers, form requests, resource classes — and infers the OpenAPI spec automatically. It requires zero docblocks for basic coverage and understands Laravel conventions deeply. For a legal-tech portal I built, Scramble correctly inferred request/response schemas from Form Requests without any manual annotation, saving hours of maintenance.

Scribe (knuckleswtf/scribe) takes a hybrid approach. It extracts structure from code but relies on strategic docblocks and configuration for richer descriptions, authentication flows, and example values. Scribe excels when you need narrative context, grouped endpoints, or multi-language code samples that pure inference cannot provide.

Installing and Configuring Scramble

composer require dedoc/scramble --dev

php artisan vendor:publish --provider="Dedoc\Scramble\ScrambleServiceProvider" --tag="scramble-config"

In config/scramble.php, restrict documentation to API routes and set your server URL:

'api_path' => 'api',
'servers' => [
    ['url' => env('APP_URL'), 'description' => 'Production'],
],
'info' => [
    'title' => 'Legal Services API',
    'version' => '1.0.0',
    'description' => 'Client portal and case management endpoints',
],

Generate the spec with php artisan scramble:export --output=storage/api-docs/openapi.json. Integrate this command into your CI pipeline so the spec regenerates on every merge to main.

Installing and Configuring Scribe

composer require knuckleswtf/scribe --dev

php artisan scribe:install

Scribe creates .scribe/ directory with intro markdown, auth config, and endpoint grouping. Run php artisan scribe:generate to produce both OpenAPI JSON and static HTML. The key advantage is @group and @authenticated annotations that organise endpoints logically — critical for complex systems like notary service portals with distinct public and client-facing sections.

Laravel CodeRoutes + RequestsScrambleScribeopenapi.jsonOpenAPI 3.x SpecSwagger UIRedoc
OpenAPI generation pipeline: Laravel code flows through Scramble or Scribe to produce a single JSON spec consumed by both renderers

What Is the Difference Between Redoc and Swagger UI for Laravel APIs?

Both tools render the same OpenAPI specification, but they optimise for fundamentally different use cases. Understanding this distinction prevents costly rework later. On a recent e-commerce integration project, we shipped Swagger UI for internal QA testers who needed to execute requests daily, while external partners received a Redoc-hosted reference because they primarily read specs before writing their own integration code.

CriteriaSwagger UIRedoc
Primary purposeInteractive testing & explorationReadable reference documentation
Try-it-out consoleBuilt-in, full HTTP clientNot included (read-only)
Visual designFunctional, dated aestheticModern, three-column layout
Search & navigationBasic tag filteringFull-text search, nested sidebar
Bundle size~3 MB uncompressed~1.5 MB uncompressed
CustomisationCSS overrides, plugin systemTheme object, React component API
Best audienceInternal devs, QA, API consumers testing liveExternal partners, onboarding, public docs
LicensingApache 2.0 (fully open)MIT (open core), paid Redocly for advanced features

Swagger UI’s try-it-out feature is genuinely valuable during development and QA. Testers can authenticate, modify parameters, and inspect responses without Postman. But for published documentation that external developers reference while building integrations, Redoc’s typography, code sample placement, and navigational hierarchy reduce cognitive load significantly. Neither is universally better; choose based on who reads your docs and why.

How Do You Serve API Documentation with Redoc and Swagger UI in Production?

Never expose documentation generators or raw spec files directly in production. Build static assets during deployment and serve them as versioned, cacheable HTML. This approach eliminates runtime PHP overhead, removes dependency on dev-only packages, and ensures docs match the exact deployed API version.

Static Generation in CI/CD

Add spec generation to your GitLab CI or GitHub Actions pipeline. For projects using Deployer 7 — a pattern I use across multiple sister sites sharing infrastructure — add a build step before deployment:

# .gitlab-ci.yml excerpt
generate-docs:
  stage: build
  script:
    - composer install --no-dev --optimize-autoloader
    - php artisan scramble:export --output=public/docs/openapi.json
    - npx @redocly/cli build-docs public/docs/openapi.json -o public/docs/index.html
  artifacts:
    paths:
      - public/docs/

This produces a self-contained index.html plus the spec file. Deploy these as static assets alongside your Laravel application. Configure Nginx or Apache to serve /docs/* directly without hitting PHP-FPM:

# Nginx snippet
location /docs/ {
    alias /var/www/current/public/docs/;
    try_files $uri $uri/ =404;
    expires 1h;
    add_header Cache-Control "public, immutable";
}

Authentication and Access Control

Public APIs can expose docs openly. For client portals, legal-tech platforms, or internal tools, protect documentation behind authentication. Serve docs through a Laravel route with middleware rather than static files:

Route::middleware(['auth:sanctum'])->group(function () {
    Route::get('/docs', function () {
        return response()->file(public_path('docs/index.html'));
    });
});

For sensitive APIs, consider environment-gated documentation entirely. Only generate and deploy docs to staging environments, keeping production completely private. This is especially relevant for Nepal-based legal services where client confidentiality obligations extend to API surface visibility.

Public API Docs (Static)CI PipelineCDN / NginxBrowserNo PHP runtime • Cacheable • Zero authPrivate API Docs (Authenticated)Laravel RouteSanctum AuthAuthorized UserMiddleware protected • Version gated • Audit loggedShared FoundationSame openapi.json generated once in CI → consumed by both serving strategiesSpec version pinned to git commit hash for traceabilityRegenerate on every merge to main — never edit manually
Production serving strategies: static public docs versus authenticated private docs, both consuming the same CI-generated OpenAPI spec

How Do You Keep API Documentation with Redoc and Swagger UI Accurate Over Time?

Documentation rot is the default state. Without enforcement, specs diverge from code within weeks. Treat documentation accuracy as a CI gate, not a hope. For a REST API built in Laravel, I enforce three non-negotiable rules that have prevented drift across multiple production systems.

  1. Fail CI on spec generation errors. If Scramble or Scribe throws exceptions during export, the pipeline must fail. Silent failures mean broken docs ship unnoticed. Add --strict flags where supported and validate output with @redocly/cli lint.
  2. Version specs with your code. Embed the git commit hash or release tag in the OpenAPI info.version field. When a partner reports unexpected behaviour, you can immediately identify which API version they integrated against. This matters enormously for legal-tech platforms where regulatory changes force breaking API updates.
  3. Test examples against real responses. Scribe supports response assertions that hit your test database during generation. Scramble integrates with Pest/PHPUnit for similar validation. If your documented example payload doesn’t match what the endpoint actually returns, generation fails. This catches schema drift before deployment.

Beyond automation, establish ownership. Assign documentation review to the same person reviewing controller logic. In small teams — common in Nepal’s development landscape — this often means you. Resist treating docs as a post-launch cleanup task. Budget documentation time into every API ticket. A full-stack developer in Nepal handling both backend and frontend integration feels this pain most acutely; accurate docs are force multipliers when you’re the sole maintainer.

Handling Breaking Changes Gracefully

When breaking changes are unavoidable, maintain parallel documentation versions. Serve /docs/v1/ and /docs/v2/ simultaneously during migration periods. Redocly’s CLI supports bundling multiple specs; Swagger UI can be configured with a spec selector dropdown. Communicate deprecation timelines explicitly in both the spec (deprecated: true) and human-readable changelogs. For Nepal-based clients operating on tight budgets, extended dual-version support is often more practical than forcing immediate migration.

Which Tool Should You Choose for Your Next Laravel Project?

The decision matrix is straightforward once you separate concerns. Use this framework when evaluating API authentication and documentation together, since auth complexity heavily influences renderer choice.

  • Choose Scramble + Redoc when your API follows Laravel conventions closely, you want minimal annotation overhead, and your primary audience reads docs more than they test interactively. Ideal for public APIs, partner integrations, and mature internal services where stability matters over exploration.
  • Choose Scribe + Swagger UI when you need rich narrative context, multiple authentication schemes, custom code samples in languages beyond cURL, or heavy interactive testing during QA. Better for complex B2B platforms, APIs with non-standard patterns, or teams still stabilising their contract.
  • Use both renderers when audiences differ. Generate one spec, publish Redoc externally and Swagger UI internally. The marginal cost is near-zero since both consume identical OpenAPI JSON. This is my default recommendation for any project with both internal developers and external consumers.

Avoid over-engineering early. Start with Scramble’s zero-config defaults. Add Scribe only when you hit concrete limitations — usually around authentication documentation or multi-language samples. Premature documentation infrastructure adds maintenance burden without proportional value, especially for startups and SMEs operating with constrained resources.

Start: New Laravel APIFollows Laravel conventions?Yes → ScrambleNo / Complex → ScribeStandard CRUDCustom auth / narrativePrimary: Read-only reference?Need interactive testing?→ Redoc→ Both→ Swagger UI→ BothYesMixedYesMixed
Decision tree: choose Scramble or Scribe based on convention adherence, then select Redoc, Swagger UI, or both based on audience needs

Implementing API Documentation with Redoc and Swagger UI Correctly

Accurate, maintainable API documentation with Redoc and Swagger UI is an engineering discipline, not a documentation afterthought. Generate specs from code, not manual YAML. Serve static assets in production, never runtime generators. Gate documentation accuracy in CI with the same rigour as test coverage. Choose renderers based on audience behaviour, not aesthetics.

If you’re building a Laravel API and struggling with documentation strategy, spec generation, or production serving architecture, reach out to discuss your project. I’ve implemented these patterns across legal-tech portals, e-commerce platforms, and service directories — and can help you avoid the pitfalls that waste weeks of rework.

Frequently Asked Questions

Swagger UI provides interactive API testing directly in the browser, while Redoc focuses on clean, three-column static documentation for reading. I typically use Swagger UI during development for debugging endpoints and Redoc for public-facing developer portals where readability matters more than interactivity.

Use the dedicated-openapi-generator or l5-swagger package to parse PHPDoc annotations into valid OpenAPI 3.0 specifications. In my experience with Laravel 12 projects, combining these with Form Request validation classes reduces manual spec maintenance significantly since your validation rules already define the contract accurately without duplicating schema definitions elsewhere.

Yes, the core Redoc library is MIT-licensed and free for commercial use. The paid Redocly platform adds features like API governance, linting, and hosted docs. For most Nepal-based client projects I have shipped, the open-source version paired with a simple Nginx configuration handles production documentation needs perfectly without recurring licensing costs.

Absolutely. Both are static HTML/JS bundles that run entirely client-side. On production Ubuntu servers, I serve them via Apache or Nginx as plain static files from the public directory. This eliminates Node.js runtime dependencies, reduces memory footprint, and simplifies deployment pipelines since you only need to copy generated HTML artifacts during release.

Never expose interactive Swagger UI publicly without authentication. Use HTTP Basic Auth, IP whitelisting, or Laravel middleware to restrict access. On legal-tech portals handling sensitive data, I disable Swagger UI entirely in production and serve only read-only Redoc behind authentication to prevent unauthorized endpoint probing or accidental data exposure through example requests.

Redoc generally outperforms Swagger UI for specs exceeding 50 endpoints due to lazy loading and virtualized rendering. Swagger UI loads everything upfront, causing browser lag on complex APIs. For a recent marketplace project with over 120 endpoints, switching to Redoc reduced initial page load from eight seconds to under two seconds on mid-range devices.

Generate specs during the build step using artisan commands, then commit or upload artifacts before deployment. With Deployer 7 and GitLab CI, I run the generator in the pipeline, validate output with spectral, and deploy static docs alongside application code. This ensures documentation always matches the deployed version without requiring server-side generation at runtime.

Swagger UI supports OpenAPI 3.1 fully from version 5.x onward. Redoc added stable 3.1 support in late 2024. Always verify your generator outputs compatible syntax, as some older Laravel packages still default to 3.0. In practice, sticking to 3.0 ensures maximum compatibility across both renderers unless you specifically need JSON Schema draft 2020-12 features.

Yes, Redoc accepts a theme object in its initialization options allowing full control over colors, typography, and spacing. I regularly override primary colors and fonts to match client branding on projects like Adventure Third Pole Trek. Unlike Swagger UI which requires CSS overrides, Redoc's theme API provides structured customization without fighting specificity wars or breaking after updates.

Maintain separate OpenAPI spec files per version and use a dropdown selector or URL routing to switch between them. For Laravel applications supporting v1 and v2 simultaneously, I generate versioned specs via route groups and serve them at /docs/v1 and /docs/v2. This prevents confusion and ensures developers always reference the correct contract for their integration target.

Usually CORS misconfiguration or incorrect server URLs in the spec. Ensure your Laravel CORS middleware allows the documentation origin and that the servers array uses absolute URLs matching your production domain. Relative paths often break when docs are served from a subdirectory. I have resolved this repeatedly by explicitly setting server URLs in the OpenAPI config rather than relying on auto-detection.

Generate from code whenever possible. Manual specs drift from implementation quickly, especially in agile teams. Using annotation-based generators tied to Laravel controllers and Form Requests keeps docs synchronized with actual behavior. I only write manual specs for third-party integrations where I lack source access. The slight setup cost pays off immediately in reduced documentation debt and fewer support tickets.

Initial setup with automated generation typically costs Rs 25,000 to Rs 60,000 (USD 190–450) depending on API complexity. Ongoing maintenance adds Rs 5,000–15,000 monthly if included in retainer. For smaller projects, I often bundle documentation with API development since the marginal effort is low once generators are configured. Avoid vendors quoting lakhs for basic Redoc/Swagger setups.

Yes, using x-codeSamples vendor extensions in your OpenAPI spec. This displays language-specific examples alongside endpoint descriptions. I generate these programmatically from test fixtures to ensure accuracy. While Swagger UI shows curl examples by default, Redoc's tabbed interface supports Python, JavaScript, PHP, and others natively, making integration guides significantly more useful for external developers consuming your API.

Choose Stoplight when non-developers need to design APIs visually or when you require built-in mocking and contract testing. Redoc and Swagger UI are renderers, not editors. For pure documentation of existing Laravel APIs, they remain simpler and cheaper. I recommend Stoplight only for API-first workflows where specification precedes implementation, not for documenting established codebases where generation from source is more reliable.

Share this article

Quick Contact Options
Choose how you want to connect me: