APIs
Note
An API (application programming interface) makes data accessible. This data takes a specific form and state. Data can be accessed repeatedly, for example so that changes which have been made in between can be made visible. To access some APIs the user must prove that they are allowed to access the API, similar to a ticket which must shown to access the cinema. This authorization can be attained on request from the employees of the chair (Lehrstuhl).
The chair itself provides the API, which is accessible after prior agreement. After that, some data is made available. Access is regulated through so-called tokens. A token is a unique key (like a ticket). It looks like a random assortment of symbols.
Attention
This token (and all other tokens) should never be shared and thus are also not meant to be commited via code.
We want to import the tokens before executing our code, so that we don't have to write them into our code explicitly. This works through so-called environment variables. Environment variables make it possible to add values to programs on execution. Our goal is the following:
- Set your token as a (local) environment variable.
- Importing this environment variable into the script.
- Using it as a variable in the script
There are two possibilities to achieve 1.:
Environment Variables via IDE
A lot of IDEs make it possible to define environment variables when executing python. If you are using one of those IDEs, you can probably find a tutorial online. Here are some tutorial site that explain how to set environment variables:
.env
Next to the IDE there is an independent option: The creation of a .env-file.
This file consists of a list of environment variables, which are listed underneath each other.
It makes sure that the token is not included into the scripts and thus not in the versioning.
This file must never be committed, but excluded via .gitignore.
The content of the .env looks like this:
WDC_TOKEN=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH
DSSCODE_TOKEN=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH
Further variables can be added underneath. Variables from the .env are
prioritized over general environment variables.
Note
To do this, you need the package dotenv, which you need to install beforehand with the package manager of your choice.
Using environment variables
To transfer the value of an environment variable into a python variable, we can use pythons built in packages:
Note
If you're using a .env-file, you first have to import the file with load_dotenv().
You have now transfered your environment variable DSSCODE_TOKEN into the python variable
dsscode_token and can pass it to other methods.