How to create a Python application that will warn you when an asteroid is approaching
![NASA API registration form screen.](https://habrastorage.org/getpro/habr/upload_files/a46/aee/8f5/a46aee8f5a4e576ff11d117acbe21f25.jpeg)
Please note that most protocols have an API limit of 1,000 requests per hour. They are suitable for testing and personal use, but not for commercial purposes.
Exploring data from NASA API
Let's look at the data returned by the API to build our use case.
Request (GET):
start_date (YYYY-MM-DD) — start date of the asteroid search
end_date (YYYY-MM-DD) — end date of the asteroid search
api_key — the key you received via email in the previous step
Answer:
Returns a JSON object containing valuable data that needs to be manipulated to produce a result.
{
"links": {
"next": "http://api.nasa.gov/neo/rest/v1/feed?start_date=2023-10-17&end_date=2023-10-17&detailed=false&api_key=8DaCUyeKqnNbupBJvDO42iUMS6tqfLFK4JjM263G",
"prev": "http://api.nasa.gov/neo/rest/v1/feed?start_date=2023-10-15&end_date=2023-10-15&detailed=false&api_key=8DaCUyeKqnNbupBJvDO42iUMS6tqfLFK4JjM263G",
"self": "http://api.nasa.gov/neo/rest/v1/feed?start_date=2023-10-16&end_date=2023-10-16&detailed=false&api_key=8DaCUyeKqnNbupBJvDO42iUMS6tqfLFK4JjM263G"
},
"element_count": 10,
"near_earth_objects": {
"2023-10-16": [
{
"links": {
"self": "http://api.nasa.gov/neo/rest/v1/neo/2337558?api_key=8DaCUyeKqnNbupBJvDO42iUMS6tqfLFK4JjM263G"
},
"id": "2337558",
"neo_reference_id": "2337558",
"name": "337558 (2001 SG262)",
"nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=2337558",
"absolute_magnitude_h": 19.33,
"estimated_diameter": {
"kilometers": {
"estimated_diameter_min": 0.3618719966,
"estimated_diameter_max": 0.8091703835
},
"meters": {
"estimated_diameter_min": 361.8719965994,
"estimated_diameter_max": 809.1703835499
},
"miles": {
"estimated_diameter_min": 0.2248567644,
"estimated_diameter_max": 0.5027950104
},
"feet": {
"estimated_diameter_min": 1187.2441213233,
"estimated_diameter_max": 2654.758561166
}
},
"is_potentially_hazardous_asteroid": true,
"close_approach_data": [
{
"close_approach_date": "2023-10-16",
"close_approach_date_full": "2023-Oct-16 16:00",
"epoch_date_close_approach": 1697472000000,
"relative_velocity": {
"kilometers_per_second": "20.8203253059",
"kilometers_per_hour": "74953.171101087",
"miles_per_hour": "46572.9856766726"
},
"miss_distance": {
"astronomical": "0.2519750156",
"lunar": "98.0182810684",
"kilometers": "37694925.626976772",
"miles": "23422540.6669605736"
},
"orbiting_body": "Earth"
}
],
"is_sentry_object": false
},
[...]
Please note the structure of near_earth_objects with the necessary details:
estimated_diameter — diameter of the asteroid in meters, kilometers, miles and feet
relative_velocity – relative speed of the object
miss_distance — distance from the orbital body
orbiting_body – in most cases this is Earth, but you can explore other options if you wish
Finding Nearby Asteroid Data Using Python Application
NASA API provides information about objects passing nearby. We will find the nearest one to send you a daily SMS alert. We use Python and the library for this requests. If you don't already have Python installed, download it from official website.
To install the requests library, enter the following command:
$ python -m pip install requests
Create a new file, for example alert.py. Import the installed requests library to send requests to the API. Also add a date object from the standard datetime module to get today's date:
import requests
from datetime import date
Get today's date using the imported module in the format needed to send an HTTP request to NASA:
# Сегодняшняя дата
todays_date = date.today().strftime("%Y-%m-%d")
Enter the API key and URL to connect to the NASA API. You need to get a free API key Here:
nasa_api_key = "NASA_API_KEY"
nasa_url = "https://api.nasa.gov/neo/rest/v1/feed?start_date=" + todays_date +"&end_date="+ todays_date + "&api_key="+nasa_api_key
Send a GET request to the NASA API and convert the response to JSON format:
# Отправляем запрос в NASA API и получаем ответ в JSON
nasa_response = requests.get(nasa_url)
json_nasa_response = nasa_response.json()
In the response received from NASA, you need to find the closest asteroid to Earth in the array near_earth_objects. Write a function to find the index of the closest asteroid in the array of all asteroids close to Earth:
# Функция для нахождения индекса ближайшего к Земле астероида в массиве всех близких астероидов
def find_closest_asteroid_index(near_asteroids):
# пустой массив для учёта дальности астероидов от Земли
asteroids = []
# перебираем астероиды в массиве near_earth_objects
for i in range(0, len(near_asteroids)):
# добавляем расстояние до Земли в массив
asteroids.insert(i, near_asteroids[i]['close_approach_data'][0]['miss_distance']['kilometers'])
# находим минимальное расстояние в массиве и возвращаем его индекс
# индекс будет совпадать с индексом ближайшего астероида в near_earth_objects
return asteroids.index(min(asteroids))
Sending an SMS notification with data about the nearest asteroid
Next, you need to send an SMS notification if the NASA API reports that there are asteroids near Earth. Check if there is an array near_earth_objects in the response from NASA API. If there is, get a list of all nearby asteroids and find the index of the nearest one using the function you wrote earlier:
# Если около Земли есть астероиды
if "near_earth_objects" in json_nasa_response:
# Получаем список близких астероидов
near_asteroids = json_nasa_response['near_earth_objects'][todays_date]
# Индекс ближайшего астероида
closest_asteroid_index = find_closest_asteroid_index(near_asteroids)
Get the data of the nearest asteroid, which we will send in an SMS notification:
# Получаем данные астероида, которые отправим в SMS-уведомлении
name = near_asteroids[closest_asteroid_index]['name'] #название астероида
how_close = near_asteroids[closest_asteroid_index]['close_approach_data'][0]['miss_distance']['kilometers'] #расстояние от Земли
diameter = near_asteroids[closest_asteroid_index]['estimated_diameter']['meters']['estimated_diameter_max'] #диаметр астероида
Translate the received data into a string and generate the message text:
# Форматируем данные в строку
how_close_str = str(round(float(how_close)))
diameter_str = str(round(diameter))
# Формируем сообщение
alert ="Ближайший астероид сегодня - " + name + ". Он находится в " + how_close_str + " км от Земли. Его диаметр составляет " + diameter_str + " метров."
Now you can proceed to sending SMS notifications using Exsolve SMS API. For this we need:
Add the Exolve number, URL, API key and recipient number to the code:
# Настройки подключения к Exolve
exolve_number = "7999XXXXXXX"
exolve_url = "https://api.exolve.ru/messaging/v1/SendSMS"
recipient_number = "7924XXXXXXX"
exolve_api_key = "EXOLVE_API_KEY"
Make a request to the Exolve API using the requests library to send an SMS notification to the specified number with the previously generated message text with data about the nearest asteroid:
# Отправляем запрос в EXOLVE SMS API и получаем ответ в JSON
exolve_response = requests.post(exolve_url,
headers = {"Authorization": "Bearer " + exolve_api_key},
json = {
"number": exolve_number,
"destination": recipient_number,
"text": alert
})
json_exolve_response = exolve_response.json()
print(json_exolve_response) # message_id или ошибка отправки
Run the code. You should receive an SMS notification similar to this:
![SMS notification SMS notification](https://habrastorage.org/getpro/habr/upload_files/e88/763/62d/e8876362d8747d8a5543f9a7fc49d4d6.png)
Summary
Let's summarize what we did:
We received an API key for the NASA OpenAPI portal.
We studied the NeoWs API, which gives access to information about asteroids heading towards Earth.
We found the closest object to our planet out of all those that could pass nearby.
Sent an SMS notification to alert yourself to this meeting.
Now you can sleep soundly, knowing that you know about every large object flying towards the Earth.
The application source code can be found at GitHub.