Fetch Prayer Times with Python
This post shows you how to pull prayer times from UmmahAPI using Python. You will go from a single API call to a working command-line tool that prints today's salah times for any city.
What you need
You only need Python 3.7 or later and the requests library. If you do not have it yet, install it with pip:
pip install requests
That is the only dependency. UmmahAPI does not require an API key to get started, so you can make your first call right now. If you plan to run this in production or hit the API frequently, grab a free key at ummahapi.com/register. The free key removes the rate limit of 5,000 requests per 15 minutes.
Your first prayer times request
The prayer times endpoint takes a latitude and longitude. It returns times for today by default. Here is the simplest possible request:
import requests
url = "https://ummahapi.com/api/prayer-times"
params = {
"lat": 21.42,
"lng": 39.82 # Makkah
}
response = requests.get(url, params=params)
data = response.json()
print(data)
The response is a JSON object. The fields you care about are Fajr, Sunrise, Dhuhr, Asr, Maghrib, and Isha. Each value is a time string like "05:13".
To print just the prayer times, pull those fields out of the response:
import requests
url = "https://ummahapi.com/api/prayer-times"
params = {"lat": 21.42, "lng": 39.82}
response = requests.get(url, params=params)
data = response.json()
prayers = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
for prayer in prayers:
print(f"{prayer}: {data[prayer]}")
Run that and you will see something like:
Fajr: 05:13
Sunrise: 06:30
Dhuhr: 12:18
Asr: 15:41
Maghrib: 18:05
Isha: 19:35
Adding error handling
Network calls fail. The server might be slow, you might pass bad coordinates, or you might hit the rate limit. Handle those cases before using the data.
import requests
from requests.exceptions import RequestException
def get_prayer_times(lat, lng):
url = "https://ummahapi.com/api/prayer-times"
params = {"lat": lat, "lng": lng}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status() # raises an error for 4xx/5xx
return response.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e.response.status_code}")
except requests.exceptions.ConnectionError:
print("Could not connect. Check your internet connection.")
except requests.exceptions.Timeout:
print("Request timed out after 10 seconds.")
except RequestException as e:
print(f"Something went wrong: {e}")
return None
times = get_prayer_times(21.42, 39.82)
if times:
print(times["Fajr"])
The timeout=10 argument stops the request from hanging forever. The raise_for_status() call turns a 429 or 500 response into a Python exception so you catch it in one place.
Tip. If you get a 429 response, you have hit the rate limit. Register for a free API key at ummahapi.com/register and pass it as a header or query parameter as shown in the API docs.
Converting a city name to coordinates
The API takes lat/lng, not a city name. You need to convert a city name to coordinates first. The standard way to do this in Python is with the geopy library and its Nominatim geocoder, which uses OpenStreetMap data for free.
pip install geopy
from geopy.geocoders import Nominatim
def city_to_coords(city_name):
geolocator = Nominatim(user_agent="prayer-times-app")
location = geolocator.geocode(city_name)
if location:
return location.latitude, location.longitude
return None, None
lat, lng = city_to_coords("London")
print(lat, lng) # 51.5074, -0.1278
Nominatim is free but has a usage policy. For a personal tool or low-traffic app, it works fine. Check the Nominatim usage policy before using it in a public app.
Fetching a full month of prayer times
If you want prayer times for every day in a month, add month and year to your request. The API returns an array of daily time objects.
import requests
def get_monthly_times(lat, lng, month, year):
url = "https://ummahapi.com/api/prayer-times"
params = {
"lat": lat,
"lng": lng,
"month": month,
"year": year
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
return response.json()
october = get_monthly_times(51.51, -0.13, 10, 2026)
# Print Fajr time for each day
for day in october:
date = day.get("date", "unknown")
fajr = day.get("Fajr", "--")
print(f"{date} Fajr: {fajr}")
This is useful for building a monthly prayer timetable that you can export to a file or display in a dashboard.
Checking calculation methods
Different organisations use different rules for calculating prayer times. UmmahAPI supports 23 methods. You can fetch the full list to show your users a picker.
import requests
response = requests.get("https://ummahapi.com/api/prayer-times/methods", timeout=10)
methods = response.json()
for method in methods:
print(method["id"], "-", method["name"])
Once you know the method ID, pass it as a method query parameter when fetching times. Check the API docs for the exact parameter name and accepted values.
Building a command-line prayer time tool
Now put everything together. This script takes a city name as a command-line argument and prints today's prayer times for that city.
import sys
import requests
from requests.exceptions import RequestException
from geopy.geocoders import Nominatim
PRAYER_TIMES_URL = "https://ummahapi.com/api/prayer-times"
PRAYERS = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
def city_to_coords(city):
geolocator = Nominatim(user_agent="prayer-times-cli")
location = geolocator.geocode(city)
if location is None:
print(f"Could not find coordinates for '{city}'.")
sys.exit(1)
return location.latitude, location.longitude
def fetch_times(lat, lng):
try:
resp = requests.get(
PRAYER_TIMES_URL,
params={"lat": lat, "lng": lng},
timeout=10
)
resp.raise_for_status()
return resp.json()
except requests.exceptions.HTTPError as e:
print(f"API error: {e.response.status_code}")
sys.exit(1)
except RequestException as e:
print(f"Network error: {e}")
sys.exit(1)
def main():
if len(sys.argv) < 2:
print("Usage: python prayer_times.py <city name>")
sys.exit(1)
city = " ".join(sys.argv[1:])
print(f"Getting prayer times for: {city}\n")
lat, lng = city_to_coords(city)
times = fetch_times(lat, lng)
max_len = max(len(p) for p in PRAYERS)
for prayer in PRAYERS:
label = prayer.ljust(max_len)
print(f" {label} {times.get(prayer, '--')}")
if __name__ == "__main__":
main()
Save this as prayer_times.py and run it like this:
python prayer_times.py New York
python prayer_times.py Kuala Lumpur
python prayer_times.py Cairo
Each command prints a clean table of today's prayer times for that city. The city name can be multiple words because the script joins all the arguments together.
Tip. You can schedule this script with cron or Windows Task Scheduler to send yourself a daily prayer time reminder. Pipe the output into a notification tool like notify-send on Linux or use the plyer Python package for cross-platform desktop notifications.
Saving times to a file
If you want to store the results or share them, you can write the data to a JSON or CSV file. Here is a quick way to save a full month to CSV using only the Python standard library:
import csv
import requests
def save_monthly_csv(lat, lng, month, year, filename):
url = "https://ummahapi.com/api/prayer-times"
params = {"lat": lat, "lng": lng, "month": month, "year": year}
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
days = resp.json()
fields = ["date", "Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
with open(filename, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
writer.writeheader()
writer.writerows(days)
print(f"Saved {len(days)} days to {filename}")
save_monthly_csv(51.51, -0.13, 10, 2026, "london_october_2026.csv")
The extrasaction="ignore" argument tells the CSV writer to skip any fields in the API response that are not in your fields list. This keeps the output clean without needing to filter manually.
FAQ
How do I get prayer times using Python?
Use the requests library to send a GET request to https://ummahapi.com/api/prayer-times with lat and lng query parameters. The response includes all six prayer times for today. See the examples above for working code.
Do I need an API key to fetch prayer times?
No. UmmahAPI works without a key up to 5,000 requests per 15 minutes. If you need more than that, register for a free key at ummahapi.com/register. The free key gives you unlimited requests.
Can I get prayer times for a full month using Python?
Yes. Add month and year to your request parameters. For example, passing month=10 and year=2026 returns prayer times for every day in October 2026. The example in the "Fetching a full month" section above shows exactly how to do it.
Which calculation methods does UmmahAPI support for prayer times?
UmmahAPI supports 23 calculation methods. Call GET /api/prayer-times/methods to get the full list with IDs and names. You can then pass the method ID as a parameter when fetching times. See the Prayer Times API page for more details.
Start building with UmmahAPI
UmmahAPI is a free Islamic API with prayer times, Quran, Hadith, Qibla, and more, all in one place.
Read the docs