Quick local API docs with Scalar
The script:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "argparse",
# ]
# ///
import glob
import subprocess
import random
port = random.randint(0,500) + 3000;
# Add your own fudge/expansion magic here if you have APIs to find
path = f'../api-*/oas/*.oas.yaml'
url = f'http://localhost:{port}'
files = glob.glob(path)
if len(files) > 0:
for f in files: # works for one match
# copy URL to clipboard for convenience
subprocess.run(["pbcopy"], input=url, text=True)
subprocess.run(["scalar", "document", "serve", "-p", str(port), f])
else:
print("API not found");
I’m using Python and I run this script with uv because I run this script from lots of different folders and it takes care of dependencies so neatly (confession: my actual script uses argparse and some inputs to feed the “guess the location of the API file from these three digits” magic but that part probably isn’t useful to other people!)
First I generate a random port number and use it to construct a URL – there’s no checking that the port is available but given that I rarely have more than 4 or 5 of these up at one time, it rarely collides and I just run the script again if it does!
The subprocess
calls then run the commands I would actually run myself on the commandline if I didn’t use a script to generate a random port number and do some path fudging logic for me:
- `pbcopy http://localhost:3333` (run this command first because the next one blocks)
scalar document serve -p 3333 openapi.yaml
Then I have the URL and can paste it into my browser. You could just open a browser tab instead of copying but I find it always picks the wrong tab/window/app/whatever so in my clipboard is more useful to me. I also use a clipboard history tool so it isn’t a problem to have lots of things writing to my copy buffer.
Feel free to adapt the script to fit your own paths and preferred tools; probably some of you do this often enough that it’s worth having a wrapper rather than remembering the correct incantation or relying on a hosted platform to download and upload to when the file is already local. And as always, if you do something differently, I’d love to hear about it!