Last active
May 15, 2025 16:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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