I was wondering how I can get ESG data for the last 19 years for firms headquartered in the US using Python API.
The code snippet shown by Wasin will get you the historical ESG data for any instrument. If you don't already have a list, and need to find the companies headquartered in the US, then you can search for those using the screener query, by specifying the filter item: TR.HeadquartersRegion. See this article on how to use screener in python.
You can use the RD Library to get historical ESG data.
rd.get_history(universe="LSEG.L", fields=["TR.TRESGScore","TR.TRESGCScore","TR.TRESGCControversiesScore"], interval="1Y", start="2002-01-01", end="2022-10-01")
Hope this helps