Python is a popular language that is both very easy to read, but also incredibly powerful. It makes it a great language to learning how to use APIs.
Installing Python on Mac
If you are using Mac, it is recommended to install python via brew. Follow the instructions on the linked website, then:
brew install python3
Now, you have `python3` available on your command line.
It is also recommended that you make virtual environments whenever starting a new project. There are many tutorials and alternatives to do this, but the most straight-forward way to make and use virtual environments is perhaps like this:
mk new_project
cd new_project
python3 -m venv venv_dir
The last command tells python3 to make a "venv" i.e. virtual environment inside the directory called "venv_dir" which can be any name you choose. The next step takes the contents of that directory and makes it like onto the shell:
source venv_dir/bin/activate
That provides you a sandbox environment to use python, and add packages. It ensures that all of the python3 bindings are available in the shell, and can be accessed.
Install Python on Windows
Please use the Microsoft Store to install Python 3. That will get you the command `python3` in your terminal. Now you can use the following:
python3 -m venv venv_dir
To activate the virtual environment, use:
./venv_dir/Bin/Activate
How to Launch a Python program?
Let's create a simple python file which we can execute to make sure everything is working:
echo 'print("hello world")' > hello.py
To execute python code in this environment, you only need to use `python`:
python hello.py
It should output "hello world" onto the command line.
This next (optional) step will simply upgrade the package manager, pip:
pip install pip --upgrade
Use the Requests Library
Like all programming languages, Python is able to interact with the internet by making calls onto web interfaces. It also has libraries, or packages, that are readily maintained by the open source community that "hides" many of the otherwise tedious steps from the programmer.
One such library is the requests library. Install it using the package manager, pip:
pip install requests
Here is a very hello world program, written in Python with the requests library. To use it, you will need to replace "secret" with your schools' real API token.
import requests
tld = 'com'
version = 'v2'
base_url = f'https://api.managebac.{tld}/{version}'
api_token = 'secret'
endpoint = f'{base_url}/school'
response = requests.get(endpoint, headers={'auth-token': api_token})
if not response.ok:
print(f'Got http error: {response.status_code}')
else:
# requests provides simple way to convert the string returned to "json"
# i.e. a python dictionary
content = response.json()
# Use dictionary methods to get the name of the school
root = content.get('school')
school_name = root.get('name')
print(f'Hello {school_name}')
If you get a 401 error, this means that the `api_token` value is not a valid token.