Generating and exporting API specification with Scramble
December 19, 2024
Generate and export an API specification using CLI with Scramble.
From the very beginning of Scramble, it was focused on generating API documentation on the fly: the specification is generated when you hit the /docs/api
endpoint. This keeps API documentation up-to-date and always relevant.
Scramble also has the ability to export the OpenAPI 3.1.0 specification from the CLI by running the scramble:export
command:
This command generates the api.json
file in the project’s root.
You can read more in the documentation: https://scramble.dedoc.co/usage/export.
Here are a few ideas this unlocks.
Using the exported spec for rendering the docs UI
When you hit the /docs/api
endpoint, Scramble generates the documentation from scratch. If you want to make your documentation public, you might prefer to reuse the generated specification and avoid generating it every time.
To do this, define the route for the documentation UI manually:
If you want to disable the default routes Scramble creates, call Scramble::ignoreDefaultRoutes
in one of your service providers:
CI integration and version control of the API specification
When you generate the api.json
file, you can add it to Git and commit it whenever the API changes. To avoid running the export command manually, set up your CI process to do this automatically. Here is an example config for GitHub Actions.
To simplify the CI setup, I used https://kirschbaumdevelopment.com/insights/laravel-github-actions as a reference.
First, here is the basic config for the CI to prepare the app for running the export command. In my case, this is the Scramble Demo app:
The idea is to run the export command when the application is ready and then commit the file. Here are the changes to do just that:
If the API changes, you will see the commit in your history, allowing you to view the changes made to the API.
For example, the commit that introduced the change, and here is the automatic CI commit documenting that change.
You can see the demo here: https://github.com/dedoc/demo-scramble.
scramble:export
is a handy command that allows you to export the specification. You can later render docs using it, push it to version control, or feed it into an API client generator.
Have fun!