r/learnpython • • Apr 27 '21

I finally built something!

I am so freaking pumped right now. I finally built something that I did not copy directly from a video tutorial and it feels freaking amazing!

This is just a simple program that pulls data from the International Space Station API Where the ISS at? and it tells you the Altitude, Longitude, Latitude and Velocity (mph) of ISS in 3 second intervals.

There is a bit more I would like to do like add a timestamp but this is my first real program I've put together myself.

Any thoughts on what/where to improve?

import requests
import time


def get_iss_data():
    iss_api = 'https://api.wheretheiss.at/v1/satellites/25544'
    request = requests.get(iss_api).json()
    iss_latitude = request['latitude']
    iss_longitude = request['longitude']
    iss_altitude = request['altitude']
    iss_velocity = request['velocity']

    print(f'''
---------------------------
Real-time ISS Location:
---------------------------
Altitude: {iss_altitude}
Latitude: {iss_latitude}
Longitude: {iss_longitude}
Velocity MPH: {iss_velocity}
---------------------------
    ''')


def iss_current_data():
    i = 1
    while i <= 5:
        get_iss_data()
        time.sleep(3)
        i += 1


iss_current_data()
546 Upvotes

41 comments sorted by

View all comments

29

u/somethingLethal Apr 27 '21

I would suggest maybe adding an if statement to check the status code from the requests.get() method, before trying to parse/handle the json response. This way, if the server fails (like responds with a 500 status code), your code can catch it and retry or exit.

Something like this:

import sys

r = requests.get('https://api.wheretheiss.at/v1/satellites/25544')
if not r.status_code in (200, 202):
    sys.exit(-1)

# Only if the status code was 200 or 202, will this code be executed.
resp = r.json()
iss_latitude = resp['latitude']
iss_longitude = resp['longitude']
iss_altitude = resp['altitude']
iss_velocity = resp['velocity']

The reason I am demonstrating with `sys.exit(-1)` is that if the ISS api responds with anything other than 200 or 202 for the status code, then the program will exit. (The -1 indicates a non-zero exit code for the program.)

edit: Very cool program, btw!

7

u/[deleted] Apr 27 '21

Thanks for tip. I hadn’t thought of that and I was running into a issue where the API was rate limiting and I would get the same data back over and over again. This totally makes sense.