Building a Simple Flask Web Application with OAuth Token Authentication
- Sairam Penjarla
- Aug 19, 2024
- 3 min read
In this blog post, we’ll guide you through creating a simple Flask web application that uses OAuth token authentication. This tutorial is perfect for beginners and will cover everything from setting up the project to testing the API using Postman.
Prerequisites
Before we start, make sure you have the following tools installed:
Python 3.7+
Postman: A tool for testing APIs.
Git: For cloning the project repository.
Step 1: Clone the Project Repository
First, clone the project repository from GitHub:
git clone https://github.com/sairam-penjarla/flask_project.git
cd flask_project
Step 2: Install the Required Dependencies
Navigate to the project directory and install the required dependencies using pip:
pip install -r requirements.txt
This will install all the necessary packages, including Flask and PyYAML.
Step 3: Understanding the Project Structure
Before we dive into the code, let’s take a look at the project structure:
flask_project/
│
├── app.py
├── utils.py
├── config.yaml
├── requirements.txt
├── README.md
└── Projectdocumentation.docx
app.py: The main application file where the Flask app is defined.
utils.py: A utility file containing helper functions.
config.yaml: A configuration file storing the OAuth token.
requirements.txt: A file listing the Python dependencies.
README.md: Documentation for setting up and running the project.
Projectdocumentation.docx: Detailed project documentation.
Step 4: Running the Flask Application
Now, let’s run the Flask application. In your terminal, navigate to the project directory and run:
python app.py
This will start the Flask server on http://localhost:5000.
Step 5: Testing the API with Postman
Open Postman and create a new POST request to http://localhost:5000/process.
Configuring the Request
Headers: Add an Authorization header with the value set to your OAuth token (which we’ll set up in the config.yaml file).
Body: Choose the raw option and set the format to JSON. Use the following JSON structure for the request body:
{
"param1": "example",
"param2": 123,
"param3": 4.56,
"param4": true,
"param5": "sample"
}
Sending the Request
Once the request is configured, click the Send button. If the token is valid, you should receive a response with the modified parameters.
Step 6: Deep Dive into the Code
Let’s break down the code step by step.
1. Loading Configuration (config.yaml)
What We’re Going to Learn
In this section, we’ll load the OAuth token from a configuration file. This allows us to keep sensitive information, like tokens, outside our codebase.
Code Block
import yaml
# Load configuration
with open("config.yaml", "r") as file:
config = yaml.safe_load(file)
Explanation
We use the yaml module to load the configuration from the config.yaml file. The config dictionary will contain our OAuth token, which we’ll use to validate incoming requests.
2. Defining the Utility Function (verify_token)
What We’re Going to Learn
We’ll create a utility function that checks whether the provided OAuth token matches the one stored in our configuration.
Code Block
def verify_token(provided_token: str, config_token: str) -> bool:
return provided_token == config_token
Explanation
This simple function compares the token provided in the request headers with the token stored in the configuration file. If they match, the function returns True; otherwise, it returns False.
3. Handling the POST Request
What We’re Going to Learn
We’ll define the Flask route that handles POST requests, verifies the token, and processes the input data.
Code Block
from flask import Flask, request, jsonify
import yaml
from utils import verify_token
app = Flask(__name__)
@app.route('/process', methods=['POST'])
def process_item():
# Extract token from headers
token = request.headers.get("Authorization")
if not token:
return jsonify({"error": "OAuth token missing"}), 401
# Verify the token
if not verify_token(token, config['oauth']['token']):
return jsonify({"error": "Invalid OAuth token"}), 403
# Get JSON data from request
data = request.get_json()
if not data:
return jsonify({"error": "Invalid input"}), 400
# Slightly modify the parameters
response = {
"param1": data.get("param1", "").upper(),
"param2": data.get("param2", 0) + 1,
"param3": data.get("param3", 0.0) * 1.1,
"
param4": not data.get("param4", False),
"param5": f"Modified-{data.get('param5', '')}"
}
return jsonify(response)
Explanation
Token Extraction and Verification: We extract the token from the Authorization header and verify it using our verify_token function.
JSON Data Processing: We process the input JSON data and slightly modify each parameter before returning it in the response.
Conclusion
In this tutorial, we’ve built a simple Flask web application that authenticates requests using an OAuth token. We also learned how to process and slightly modify JSON input before returning it in the response.
Feel free to customize and expand on this project for your use case!
Would you like any further customization or assistance with deployment?