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: September 2026

Shipping a REST API without current docs guarantees failed integrations and wasted developer hours. Strong API documentation with Redoc and Swagger UI starts with reliable OpenAPI regen in CI, then adds SDK PR drafts and validated examples so partners never integrate against stale contracts. This guide covers spec generation in Laravel 13, renderer choice, production serving, and the automation pipeline that keeps docs, SDKs, and code aligned.

How Do You Set Up OpenAPI Regen for API Documentation with Redoc and Swagger UI?

Before you render anything, you need a valid OpenAPI 3.x file that rebuilds on every merge. Manual YAML rots within weeks. In Laravel, Laravel API best practices now treat the spec as a build artefact, not a side document.

Scramble (dedoc/scramble) reads routes, controllers, Form Requests, and API Resources. It infers schemas with minimal annotation. On a legal-tech portal I built, Scramble mapped Form Request rules to request bodies without docblocks.

Scribe (knuckleswtf/scribe) blends code extraction with docblocks. It shines when you need grouped endpoints, auth narratives, and multi-language samples Scramble cannot infer alone. See our Scribe for Laravel guide for a deeper Scribe-only walkthrough.

Installing Scramble and wiring OpenAPI regen

composer require dedoc/scramble --dev

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

Set your API path and server URL in config/scramble.php:

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

Export the spec locally with:

php artisan scramble:export --output=storage/api-docs/openapi.json

That command is your OpenAPI regen entry point. Run it in CI on every push to main. Pair it with npx @redocly/cli lint storage/api-docs/openapi.json so broken schemas fail the pipeline before deploy. The OpenAPI 3.1 specification guide explains fields Scramble and Scribe emit.

Scribe as an alternative generator

composer require knuckleswtf/scribe --dev

php artisan scribe:install
php artisan scribe:generate

Scribe writes OpenAPI JSON plus static HTML under public/docs. Use @group, @authenticated, and @response annotations when inference falls short. For complex B2B APIs with multiple auth schemes, Scribe often saves time despite higher annotation cost.

Validated examples that block bad docs

Examples are where most API docs lie. Scribe can assert responses against your test database during generation. Scramble integrates with Pest and PHPUnit so documented payloads must match real endpoint output.

Define response examples in Form Requests or Resources, then let CI reject exports when shapes drift. A partner reading your Redoc page should copy an example and get a 200 response—not a validation error. Use the JSON formatter tool to inspect exported payloads during local review.

OpenAPI Regen PipelineLaravel CodeRoutes + RequestsScrambleScribeCI Lint + TestExamples checkedopenapi.jsonSingle source of truthSwagger UITry-it-out consoleRedocReference layoutSDK PR DraftAuto-generated clientOne spec regen feeds docs, examples, and SDK PR draftsCommit hash pinned in info.version for traceabilityNever edit openapi.json by hand after CI export
OpenAPI regen in CI produces one spec consumed by Redoc, Swagger UI, validated examples, and optional SDK PR drafts

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

Both render the same OpenAPI file. They optimise for different readers. On an e-commerce integration, we shipped Swagger UI for QA testers and Redoc for external partners who read specs before writing code.

CriteriaSwagger UIRedoc
Primary purposeInteractive testing and explorationReadable reference documentation
Try-it-out consoleBuilt-in HTTP clientRead-only (no live requests)
Visual designFunctional, familiar layoutThree-column, typography-focused
Search and navigationTag filteringFull-text search, nested sidebar
Bundle size~3 MB uncompressed~1.5 MB uncompressed
CustomisationCSS overrides, pluginsTheme object, React component API
Best audienceInternal devs, QA, live testingExternal partners, onboarding, public docs
LicensingApache 2.0 (fully open)MIT open core; Redocly for enterprise

Swagger UI’s try-it-out panel lets testers authenticate and fire requests without Postman. Redoc reduces cognitive load for developers reading schemas and copy-paste examples. Neither wins on every project. Match the renderer to who reads your docs and why. Official references: Swagger UI documentation and Redoc by Redocly.

How Do You Automate SDK PR Drafts from OpenAPI Regen?

Documentation alone is not enough when partners expect typed clients. After OpenAPI regen succeeds, generate SDK PR drafts in the same CI job. The spec becomes the contract for docs, tests, and client libraries.

CI job that regens spec and opens SDK PR drafts

# .gitlab-ci.yml excerpt
openapi-regen:
  stage: build
  script:
    - composer install --no-dev --optimize-autoloader
    - php artisan scramble:export --output=storage/api-docs/openapi.json
    - npx @redocly/cli lint storage/api-docs/openapi.json
    - npx @openapitools/openapi-generator-cli generate
        -i storage/api-docs/openapi.json
        -g php
        -o sdk/php-client/
    - git diff --quiet sdk/ || ./scripts/open-sdk-pr-draft.sh
  artifacts:
    paths:
      - storage/api-docs/
      - sdk/

The shell script creates a branch, commits SDK changes, and opens a PR labelled sdk-regen. Reviewers check breaking diffs before merge. This pattern mirrors what larger API teams call contract-first delivery. Our SDK design guide covers naming, error types, and pagination wrappers generators miss.

Pin the OpenAPI info.version to your git tag or commit hash. When a partner reports unexpected behaviour, you know exactly which spec they integrated against. For legal-tech platforms where regulatory updates force breaking changes, version traceability is non-negotiable.

Example validation as a CI gate

Add three rules after every OpenAPI regen:

  1. Lint the spec. Redocly CLI catches invalid references, missing response codes, and schema conflicts. A lint failure blocks deploy.
  2. Assert examples match responses. Scribe response assertions or Scramble plus Pest feature tests confirm documented payloads equal live output.
  3. Diff the SDK. If generated client method signatures change, the SDK PR draft must pass human review before release.

Contract tests with Pact or schema validation against staging add another layer. See API contract testing with Pact for consumer-driven patterns that complement OpenAPI regen.

Production Doc ServingPublic API DocsCI BuildNginx CDNBrowserStatic HTML, no PHP runtimePrivate API DocsLaravelSanctumUserMiddleware gated, audit loggedShared CI FoundationOpenAPI regen once per merge to mainRedoc + Swagger UI built from same openapi.json
Public static docs versus authenticated private docs, both built from the same CI OpenAPI regen output

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

Never expose runtime doc generators in production. Build static assets during deploy and serve them as cacheable HTML. This removes dev-package overhead and pins docs to the deployed API version.

Static generation in CI/CD

Add OpenAPI regen and HTML build to your pipeline. For Deployer 7 workflows I use on sister sites, run this before symlink swap:

generate-docs:
  stage: build
  script:
    - php artisan scramble:export --output=public/docs/openapi.json
    - npx @redocly/cli build-docs public/docs/openapi.json -o public/docs/index.html
    - cp node_modules/swagger-ui-dist/swagger-ui-bundle.js public/docs/swagger/
  artifacts:
    paths:
      - public/docs/

Serve /docs/* directly from Nginx without PHP-FPM:

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

Full pipeline patterns appear in our GitLab CI/CD for PHP projects and zero-downtime Deployer guide.

Authentication and access control

Public APIs can expose docs openly. Client portals and legal-tech platforms need gated access. Serve docs through a Laravel route with middleware:

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

For highly sensitive APIs, generate docs only on staging. Production stays private. This fits Nepal legal services where confidentiality extends to API surface visibility. Review Laravel Passport vs Sanctum when choosing the auth layer docs must describe.

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

Documentation rot is the default. Without enforcement, specs diverge from code within weeks. Treat accuracy as a CI gate equal to test coverage. For a REST API built in Laravel the right way, three rules prevent drift across production systems I maintain.

  • Fail CI on regen errors. Scramble or Scribe exceptions during export must fail the pipeline. Add Redocly lint with zero warnings tolerated.
  • Version specs with releases. Embed git commit hash in info.version. Partners can map behaviour to an exact deploy.
  • Test examples against real responses. If documented JSON does not match live output, block the merge. Examples are contracts, not decoration.

Assign doc review to whoever reviews controller logic. In small Nepal teams, that is often one person. Budget doc time into every API ticket. A full-stack developer in Nepal maintaining backend and integrations feels this pain most—accurate docs multiply output when you are the sole maintainer.

Breaking changes and parallel doc versions

When breaking changes ship, serve /docs/v1/ and /docs/v2/ during migration. Mark deprecated endpoints with deprecated: true in the spec. Publish human-readable changelogs beside Redoc pages. Nepal clients on tight budgets often need extended dual-version support rather than forced same-day migration.

Align error shapes with RFC 7807 problem details so examples in Redoc match what SDK PR drafts encode. Consistent error schemas reduce partner support load.

Tool Selection TreeNew Laravel API ProjectStandard conventions?Yes: ScrambleNo: ScribeRead-only audience?Need live testing?RedocBothSwagger UIBoth
Choose Scramble or Scribe first, then pick Redoc, Swagger UI, or both based on audience needs

Which Tool Stack Should You Choose for Your Next Laravel Project?

Separate spec generation from rendering. Evaluate auth complexity alongside docs, since it affects both Scribe annotations and Swagger UI try-it-out setup.

  • Scramble + Redoc + OpenAPI regen: Best when conventions are standard, annotation overhead must stay low, and partners read more than they test. Ideal for public APIs and stable internal services.
  • Scribe + Swagger UI: Best when you need auth narratives, grouped endpoints, or heavy QA testing during stabilisation.
  • Both renderers, one spec: Default when internal devs and external partners coexist. Marginal cost is near zero. Publish Redoc at /docs and Swagger UI at /docs/explore.

Start with Scramble defaults. Add Scribe only when you hit concrete limits—usually auth docs or multi-language samples. Premature doc infrastructure adds maintenance without proportional value for startups and SMEs.

For production APIs serving Nepal businesses, professional setup matters. Our API development service in Nepal covers spec design, OpenAPI regen pipelines, and partner-ready documentation. See the Mijar Law Associates client portal for a legal-tech API with document workflows and authenticated endpoints.

Manual Docs vs OpenAPI RegenBefore: Manual YAMLStale examples after 2 weeksNo SDK, partners write raw HTTPSupport tickets on every releaseAfter: CI OpenAPI RegenExamples validated in CISDK PR drafts on spec changeRedoc + Swagger UI auto-builtFixOutcome: One openapi.json drives everythingPartners integrate faster with typed SDK clientsDocs match deployed code on every release
Automated OpenAPI regen with validated examples and SDK PR drafts replaces manual doc maintenance

Security belongs in the same conversation. Document auth flows accurately and follow the OWASP API Top 10 checklist. Pair spec linting with REST API design best practices so generated SDK PR drafts expose safe, predictable interfaces. The official OpenAPI 3.1 specification remains the authoritative schema reference.

Key Takeaways

  • Run OpenAPI regen in CI on every merge—never maintain openapi.json by hand.
  • Lint specs with Redocly CLI and validate examples against real endpoint responses before deploy.
  • Generate SDK PR drafts from the same spec so client libraries stay in sync with docs.
  • Use Swagger UI for interactive testing; use Redoc for partner-facing reference documentation.
  • Serve static doc HTML in production; gate private APIs behind Sanctum or Passport middleware.
  • Pin info.version to git commits so partners can trace integration issues to exact releases.

People Also Ask

Can Redoc and Swagger UI use the same OpenAPI file?

Yes. Both consume identical JSON or YAML from your OpenAPI regen step. Build one spec in CI, then render Redoc for external readers and Swagger UI for internal testers. Dual publishing costs little because the spec is already generated.

How often should you regenerate OpenAPI specs in CI?

Regenerate on every merge to your main branch at minimum. Regenerate on every pull request when API routes change. Pair regen with lint and example tests so broken schemas never reach production documentation.

What are SDK PR drafts in an OpenAPI workflow?

SDK PR drafts are auto-generated pull requests that update client libraries when the OpenAPI spec changes. Tools like OpenAPI Generator read the new spec, diff the output, and open a PR for human review before partners receive updated typed clients.

Is Scramble or Scribe better for Laravel 13 APIs?

Scramble suits convention-heavy Laravel APIs with minimal annotation. Scribe suits APIs needing rich auth docs, custom grouping, and narrative context. Many teams start with Scramble and add Scribe only when inference limits appear.

Ship Documentation That Matches Your Code

Reliable API documentation with Redoc and Swagger UI is an engineering discipline. Regenerate OpenAPI specs in CI, validate examples, optionally open SDK PR drafts, and serve static HTML in production. Pick renderers by audience, not aesthetics.

Building a Laravel API and need help with OpenAPI regen, SDK automation, or production doc architecture? Contact us to discuss your project, or reach out directly. I have implemented these patterns on legal-tech portals, e-commerce platforms, and service directories—including work visible in our Notary Nepal portal portfolio case.

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

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: