Or is there some API service to buy Bitcoin on-the-fly?
There are APIs for that, but at that point you just become a middle-man, a mere front-page between customers and an existing exchange in the backend.
That introduces issues like heavy dependence on the service's uptime, ToS, questions about their privacy policy and more. The 'backend exchange' (Binance, etc.) will also have to make a profit on this as opposed to serving the customer directly, meaning you will have to offer worse rates.