Securing Endpoints with Dependency Injection

Securing Endpoints with Dependency Injection

Welcome back! In our previous lesson, you started to see how Dependency Injection (DI) is used in FastAPI through the use of the Depends function, particularly in the login endpoint. We didn't dive deeply into the concept at that time, but now it's time to explore it in detail.

In this lesson, we will explain what Dependency Injection is and why it's important in software development. By the end of this lesson, you'll understand how it helps to keep code clean and allows us to secure an endpoint using in FastAPI.

Understanding Dependency Injection

Dependency Injection might sound complicated, but it's a simple and powerful concept. Think of it like this: instead of a function creating everything it needs by itself, it receives those things from the outside. This way, the function doesn't worry about how to get what it needs; it just uses it. This leads to cleaner, more manageable code.

In FastAPI, we use the Depends function to handle Dependency Injection. Imagine having a function that needs certain pieces of information to work. Using Depends, we can provide those pieces of information from outside the function, making our code more organized and easier to test.

Taking Back from Where We Stopped

Let's quickly recap what we covered last time. We created a FastAPI app, set up a mock database, and implemented a user authentication function along with a login endpoint.

Here is a quick summary of the code:

Python
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

# Mock database with usernames and passwords
users_db = {"user1": "pass1", "user2": "pass2"}


# Function to check if user exists in the database
def authenticate_user(username: str, password: str):
    if users_db.get(username) == password:
        return {"username": username}
    raise HTTPException(status_code=401, detail="Incorrect username or password")


# Login endpoint
@app.post("/login")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    return authenticate_user(form_data.username, form_data.password)

Dependency Injection in the Login Endpoint

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal