Skip to content

Instantly share code, notes, and snippets.

@colehocking
Last active May 15, 2025 16:30
Show Gist options
  • Save colehocking/3a2d4bd076c8461c7d8cfe65269edf24 to your computer and use it in GitHub Desktop.
Save colehocking/3a2d4bd076c8461c7d8cfe65269edf24 to your computer and use it in GitHub Desktop.
Basic API GET in Python; token-based auth; read from config.ini file
#!/usr/bin/python3
# basic API GET request
# Token based auth; get URLs/tokens from config.ini file
# -- Cole Hocking
import configparser, requests, json, os
def read_configs(filename, header, value):
"""
Authenticate via config.ini file
:return key value in config file
"""
config = configparser.ConfigParser()
config.read(filename)
value = config[header][value]
return value
def main():
"""
main call
"""
# read a config.ini file, 2 dirs up from script
config_path = os.path.abspath(os.path.join(os.path.dirname(__file__),
'../..', 'config.ini'))
# API token from config.ini file
api_key = read_configs(config_path, 'HEADER', 'KEY')
# base URL for API
base_url = read_configs(config_path, 'HEADER', 'KEY')
# URL for specific API query
url = f'{base_url}subdir'
# Fetch API session
api_session = requests.Session()
# Add token to headers
api_session.headers = {"X-Api-Key": api_key}
try:
response = api_session.get(url)
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
sys.exit(1)
result = response.json()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment