I will be staying over for 20 hour layover and I was wondering if I needed to get a visa in order to leave airport and visit the city. And if I need a visa do I apply for it while I'm on the layover in Istanbul or can I apply for it in America before I go?
You Need a Visa to Enter Turkey
If you plan on leaving the airport then, as a US passport holder, you will need a Turkish Visa to enter the country.
United States of America: Ordinary and official passport holders are required to have visa to enter Turkey. They can obtain three month-multiple entry visas from Turkish diplomatic representations abroad and also via the website www.evisa.gov.tr.
You Don't Need a Transit Visa
Since the linked website explicitly mentions "transit" for other nationalities, I am assuming that US citizens don't need a transit visa for Turkey, if they stay within the terminal airside. Indeed, the website of the Turkish Ministry of Foreign Affairs states the same:
Question: I will be flying to Europe. I know that our aircraft will land in İstanbul. I am not planning to leave the transit lounge. Do I need to get transit visa?
Answer: If you will not leave the transit lounge at the airport you are not required to have transit visa. Otherwise, you have to make visa application to the nearest Turkish Representation. Contact information of the said missions can be reached through www.mfa.gov.tr (Ministry/Turkish Representations).