TestDriven.io Tutorial "Scalable FastAPI Applications on AWS": Part 1 API Request a Talk Endpont code doesn't work

216 Views Asked by At

I'm working through the TestDriven.io tutorial "Scalable FastAPI Applications on AWS". In part 1, Chapter "API", the code under "Request a Talk" - "Endpoint" fails, but not as expected. This is the link to the page:

https://testdriven.io/courses/scalable-fastapi-aws/api-endpoints/

The file is test_app.py and line in question is:

from web_app.app import app

When running this file, the error is "No module named web_app.app"

When I change it to import web_app.main instead (which makes more sense, since there actually is a web_app/main.py file), I get an error in the following lines:

@pytest.fixture
def client():
    app.config["TESTING"] = True

The error now is "AttributeError: 'FastAPI' object has no attribute 'config'".

Has anyone else done this tutorial up to this point and had the same issue?

2

There are 2 best solutions below

0
On BEST ANSWER

The example given is not for FastAPI, it's for Flask (and it's from the current version of Flask's examples on configuration handling):

app = Flask(__name__)
app.config['TESTING'] = True

In FastAPI you'd usually override the explicit dependency instead if necessary, and/or use environment variables to change configuration from pydantic's BaseSettings object.

Using BaseSettings:

from pydantic import BaseSettings


class Settings(BaseSettings):
    app_name: str = "Awesome API"
    admin_email: str
    items_per_user: int = 50

You can then override specific configuration settings with APP_NAME or ADMIN_EMAIL as environment variables. You can also inject the settings object as a dependency where needed, and then override that dependency when testing instead.

Overriding a dependency:

async def override_dependency(q: Optional[str] = None):
    return {"q": q, "skip": 5, "limit": 10}


app.dependency_overrides[common_parameters] = override_dependency

Given the error you've already mentioned and the example given seemingly being related to something completely different from FastAPI, I'd be wary of trusting that source material (the link is behind a sign in form, so it's not publicly available).

0
On

MatsLindh: Yes - by replacing the code with the following, I was able to get it to work:

from web_app.main import app


@pytest.fixture
def client():
    return TestClient(app)

This corresponds to how it should be done in FastAPI