Storing the API key in a Configuration file in a Python project
API key in config.ini
When you build an Web application or Mobile application using API that is Application Program Interface , We usually write the API in the main code which is not the right way of the writing the code in general.
For example : We want to build an Web application like Building a Weather Dashboard using Flask framework in Python language. We use API from openweathermap to facilitate user request by entering the city name and render the API data which is the Weather information in our Web Application.
So, this article is all about storing the API key in the separate file called Configuration file rather than storing the API key blatantly in our main code.
Let's see how we do that. So we are going to create a file called config.ini
Ini files in Python are a very easy way to store configurations and inside of this configuration file, we are going to specify that this is the Project name (For example: Open weather map) and inside of this, we have a configuration,the API key .
Now what you wand go ahead and do is install one more module called configparser and what this will allow us to do is essentially read this config.ini file and get this API key.
So we will define new function in the main code and inside of this function , we are going to go ahead and say my config to be equal to configparser.ConfigParser() and also don’t forget to import configparser at the top.
Once I have configuration file, I am going to read in ini file I just made Config.read(‘config.ini) and get the API key by saying config and inside of this the app that we just made open weather map and then the key api
So its essentially gonna open this config.ini file ,look for open weather map ,get the API value and now what I am going to do is rather than hard code this API key , I can go ahead and say get_api_key() instead shown in the image below
Now If we run the main code , we can see the exact result because we store this API key in configuration file.