A Stock Market API in 30 Minutes

Since everyone in my entire life is buying and selling GameStop this month, a friend and I started making a small app to visualize stock market data and chat with your friends. He wanted to practice Tailwind and Svelte, I wanted to use Go and GRPC....
Well, I didn't end up using Go.
I was researching the best api's to get stock market data, and realized everything I could find required signing up... This app was going to have 3... maybe 4 users ever, so it seemed like a hassle.
I realized, if I just search for {symbol} stock
Google returns this fancy stock card.

Since I've been using JS for... well... ever, I've obviously heard of, and used puppeteer before.
I thought, "sweet, Google has all the data I need, in near real-time, and Google also created Puppeteer, sounds like they've basically given me a stock market api already!"
The Solution
The core logic of my API? It's like 5 lines of code:
const getStockPrice = async (symbol) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(`https://www.google.com/search?q=${symbol}+stock`);
prices[symbol] = await page.evaluate(
() => document.querySelector("g-card-section > span")?.textContent
);
await browser.close();
};
Launch puppeteer, go to a google search with the symbol name, and then do a query selector to grab the text content of this spot:

After that, it's up to you. We can fetch this data whenever. Here's what I went with:
app.get("/stocks/:symbol", async (req, res) => {
let { symbol } = req.params;
//get the latest price in the background if we already have it in memory
if (!prices[symbol]) await getStockPrice(symbol);
else getStockPrice(symbol);
res.send({ symbol, price: prices[symbol] ?? "N/A" });
});
When you request a symbol, it will wait for puppeteer to finish if we don't have the price in memory, otherwise it'll do it in the background, this way the api response is really fast most of the time.
Production Ready?
Probably not. This seriously took 20-30 minutes though. If you wanted to make a service out if this, just scrape Vanguard, Robinhood, and a few other exchange's websites, and if one goes down or changes markup, you can be alerted and go fix it while relying on the others.
Oh yeah, that's probably against the terms of service... so don't do it... or do it anyway, I'm not your mom, or a lawyer :)
Another thing you can throw in the code:
setInterval(() => getStockPrice("gme"), 15000);
This will auto update gme every 15 seconds for you.
After that, throw in a webso.... just kidding, nobody uses those anymore, add in http/2 streaming so you can push the data in real-time to your client app, then... after all of my suggestions... maybe it's production ready?
Conclusion
I always love using Puppeteer to do interesting things. You can take a look at the full source code on GitHub. It's only 30~ lines of code and could be greatly expanded upon, enjoy!