Redevil10 / fastapi-jwt

FastAPI with JWT authentication demo
0 stars 0 forks source link

FastAPI JWT Demo

lint test coverage python

Introduction

FastAPI + JWT + SQLAlchemy + SQLite(or Postgres) demo. The code follows the official document of FastAPI OAuth2 JWT.

Run Locally

  1. Clone the repository

  2. Create virtual env and activate

    $ pyenv shell 3.11
    $ python -m venv venv
    $ source venv/bin/activate
    (venv) $ pip install -U pip
  3. Install poetry and dependencies

    (venv) $ pip install poetry
    (venv) $ poetry install
  4. Start FastAPI app locally

    (venv) $ uvicorn main:app --reload
  5. Visit http://localhost:8000/docs

  6. If running the app for the first time, the users table in the database is empty. To be able to log in and use the API, you can send a POST request to endpoint: http://localhost:8000/users/init with an empty body. This will create the default superuser defined in ./config.py.

Test

FastAPI has a built-in TestClient class which is based on pytest and requests, this makes it very easy to write tests. To run all test cases:

(venv) $ pytest

This will create a test database named fastapi_app_test.db at the beginning of the test, run all test cases, then remove the database file after finishing the last test case.