top of page

Building a Simple FastAPI Project with OAuth Token Authentication

  • Writer: Sairam Penjarla
    Sairam Penjarla
  • Aug 19, 2024
  • 3 min read

In this blog, we’ll walk you through building a simple FastAPI project that authenticates requests using an OAuth token. This tutorial is designed for beginners and will guide you step by step through setting up the project, running the API, and testing it 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/fastapi_project.git>
cd fastapi_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 FastAPI and Uvicorn.

Step 3: Understanding the Project Structure

Before we dive into the code, let’s take a look at the project structure:

fastapi_project/
│
├── app.py
├── utils.py
├── config.yaml
├── requirements.txt
├── README.md
└── Projectdocumentation.docx
  • app.py: The main application file where the FastAPI 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 FastAPI Application

Now, let’s run the FastAPI application. In your terminal, navigate to the project directory and run:

uvicorn app:app --reload

This will start the FastAPI server on http://localhost:8000.

Step 5: Testing the API with Postman

Open Postman and create a new POST request to http://localhost:8000/process.

Configuring the Request

  1. Headers: Add an Authorization header with the value set to your OAuth token (which we’ll set up in the config.yaml file).

  2. 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 Data Model (Item Class)

What We’re Going to Learn

We’ll define a data model using Pydantic, which will be used to validate and parse the incoming JSON request.

Code Block

from pydantic import BaseModel

class Item(BaseModel):
    param1: str
    param2: int
    param3: float
    param4: bool
    param5: str

Explanation

The Item class inherits from BaseModel and defines the structure of the data we expect to receive in the request body. Each parameter has a specific type (e.g., str, int, float, etc.), and Pydantic will automatically validate that the incoming data matches this structure.

3. Verifying the OAuth Token

What We’re Going to Learn

We’ll implement a function that extracts the OAuth token from the request headers and verifies it against the token in our configuration file.

Code Block

from fastapi import Request, HTTPException, Depends

def get_oauth_token(request: Request):
    token = request.headers.get("Authorization")
    if not token:
        raise HTTPException(status_code=401, detail="OAuth token missing")
    return token

@app.post("/process")
def process_item(item: Item, token: str = Depends(get_oauth_token)):
    if not verify_token(token, config['oauth']['token']):
        raise HTTPException(status_code=403, detail="Invalid OAuth token")

Explanation

  • get_oauth_token: This function retrieves the Authorization header from the incoming request. If the token is missing, it raises a 401 Unauthorized error.

  • process_item: This is the main endpoint that handles the POST request. It uses FastAPI’s Depends to ensure that the token is validated before proceeding.

4. Modifying the Parameters

What We’re Going to Learn

In this final section, we’ll modify the parameters slightly before sending them back in the response.

Code Block

    # Slightly modify the parameters
    response = {
        "param1": item.param1.upper(),
        "param2": item.param2 + 1,
        "param3": item.param3 * 1.1,
        "param4": not item.param4,
        "param5": f"Modified-{item.param5}"
    }
    return response

Explanation

Here, we take the incoming parameters and apply some simple modifications:

  • Convert param1 to uppercase.

  • Increment param2 by 1.

  • Increase param3 by 10%.

  • Toggle the boolean value of param4.

  • Prefix param5 with "Modified-".

These changes demonstrate how you can process and transform data within your API.

Step 7: Conclusion

In this blog, we’ve built a simple FastAPI application that validates requests using an OAuth token and processes user input. We’ve covered the entire workflow, from setting up the project to testing it with Postman. This foundational knowledge will help you build more complex APIs with secure authentication mechanisms in the future.

For more information, you can check out the GitHub repository.

Sign up for more like this.

Thanks for submitting!

bottom of page