r/FastAPI • • May 27 '23

Question Is there any Flask-migrate equivalent for Fastapi

1 Upvotes

Hi I am new to fastapi
I have used flask before, I handled db migrations using flask-migrate
now I have started a fastapi project is there any packages like flask-migrate

thank you for your time


r/FastAPI • • Feb 09 '23

Question Need help: In deciding framework

0 Upvotes

I want to write an API which will accept server IP as input and then run few commands on that server and return the output generated by those commands as response. Is it possible to use fastAPI for this? Also, is there any similar project available in python? I am new to python.


r/FastAPI • • Sep 24 '23

Question Return a List of images that can be viewed in the swagger UI

1 Upvotes

I have an endpoint that takes a List of uploaded images, works on them and then returns the data. I cant get the Response correct to display the final images.

I had this working for 1 image but trying to return a list of images isnt working for me. I am hoping to be able to show the images in the swagger UI as well.

TIA!

Exception

    File "/opt/zm_ml/src/zm_ml/Server/app.py", line 432, in get_annotated_image
      return Response(content=image_buffer, media_type="image/jpeg", headers={"Results": results_json}, background=None)
    File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/starlette/responses.py", line 55, in __init__
      self.body = self.render(content)
    File "/opt/zm_ml/data/venv/lib/python3.10/site-packages/starlette/responses.py", line 63, in render
      return content.encode(self.charset)
  AttributeError: 'list' object has no attribute 'encode'

Example:

@app.post(
    "/annotate",
    # Set what the media type will be in the autogenerated OpenAPI specification.
    # https://fastapi.tiangolo.com/advanced/additional-responses/#additional-media-types-for-the-main-response
    responses={200: {"content": {"image/jpeg": {}}}},
    # Prevent FastAPI from adding "application/json" as an additional
    # response media type in the autogenerated OpenAPI specification.
    # https://github.com/tiangolo/fastapi/issues/3258
    response_class=Response,
    summary="Return an annotated jpeg image with bounding boxes and labels",
)
async def get_annotated_image(
        user_obj = Depends(verify_token),
        hints_: List[str] = Body(...,
                                 example="yolov4, yolo-nas-s trt",
                                 description="A list of model names/UUIDs"),
    images: List[UploadFile] = File(...)
):
   
    if hints_:
        from ..Shared.Models.config import DetectionResults, Result

        detections: List[List[DetectionResults]]
        images: List[np.ndarray]
        detections, images = await detect(hints_, images, return_image=True)
        is_success, img_buffer = cv2.imencode(".jpg", _image)
        if not is_success:
            raise RuntimeError("Failed to encode image")
         
        # This is where I am going wrong:
        image_buffer.append(img_buffer.tobytes())


        # media_type here sets the media type of the actual response sent to the client.
        # Return the results in a header, this allows Swagger UI to display the image
        import json
        results_json = []
        for _result in detections:
            if _result:
                for _det in _result:
                    results_json.append(_det.model_dump())
        return Response(content=image_buffer, media_type="image/jpeg", headers={"Results": results_json}, background=None)

r/FastAPI • • Mar 14 '23

Question Need help with authentication

1 Upvotes

This is about the libroary FastAPI-mail.

Ok, I wrote a little project to send emails from my gmail account, created the password for google "less secure apps" and it all worked.

Then I had the great idea of formatting my computer and I didn't rememer the the .env file wasn't on my repo. Now I have created a new file and added what should be the exact same variables and values and when I try to send a mail, the process keeps on running and some time later I get:

"fastapi_mail.errors.ConnectionErrors: Exception raised Timed out connecting to smtp.gmail.com on port 587, check your credentials or email service configuration", but I can't find the cause.

my .env file is:MAIL_USERNAME=[email protected]MAIL_PASSWORD=lessSecureAppPassMAIL_FROM=[email protected]MAIL_PORT=587MAIL_SERVER=smtp.gmail.comMAIL_FROM_NAME=somename


r/FastAPI • • Dec 09 '22

Question Update current logged in user

1 Upvotes

Hello guys, I am creating an application using FastAPI. I have a problem right now, i want to update the information of the current logged in user. How would i implement that?


r/FastAPI • • Sep 21 '23

Question i need help

1 Upvotes

Hello, I am developing in fastapi and I am wanting to create a user, with attributes received as parameters in the url but I don't know how to do it, on the fastapi page they give you a code where you can do it but through /docs, I need to be able to write the parameters through url, thanks in advance.


r/FastAPI • • Dec 16 '22

Question FastAPI and Prometheus endpoint

1 Upvotes

Hi all,

I have a fastapi app which generates some custom prometheus metrics with the prometheus client library.

I can start a separate server with start_http_server method from the prometheus client, but i would like to have the /metrics endpoint be served on the same port as my fastapi app.

I cant seem to find an easy way to do this, i see a prometheus offers integration with ASGI but i cant figure out how to piece everything together. AAnyone here done this before?


r/FastAPI • • Sep 17 '22

Question FastAPI equivalent to Express' app.locals/local variables

1 Upvotes

Hi there,

Apologies in advance if this is a silly question. I'm developing an application using FastAPI for the first time (coming mostly from a Node background). There's something that I just can't figure out, but I must be overlooking it as it's a pretty common use case.

In Node's Express framework, there is an object called `locals` which is a property of the main `app` variable. This is used to store variables in memory. For example, I may run a scheduled job to fetch and parse some data and save the data in memory within `app.locals.jobData`. All request handlers are able to access this object, so you can easily use the cached data in your handler logic. For example, I could do something like:

app.get('/show_job_data', (req, res) => {
  return res.json({data: req.app.locals.jobData})
})

Is there such a tool available for FastAPI, or does it require the use of an additional package? I'm having a difficult time finding an answer in the documentation. Thanks!


r/FastAPI • • Apr 30 '23

Question FastAPI + Tortoise ORM with custom OAuth2 scopes

1 Upvotes

I'm writing a backend application with FastAPI and Tortoise-ORM for handling my database operations. I've been working with the example provided by FastAPI docs for implementing OAuth2 scopes with some divergence to use Tortoise orm for fetching the user. I've been unsuccessful in adequately trying to write a secured endpoint with the permissive scopes to return basic user information from a signed JWT token.

I'm not an experienced Python user (most backend applications I've written are in Java) so please forgive me if I might be overlooking something. I have all the necessary code written to properly generate a secure JWT and return it to the client with user information. The issue I'm running into seems to stem from `pydantic` and its internal validation. Below are the snippets of code used in the entirety of the request

User API router

@router.get("/self", response_model=Usersout_Pydantic)
async def self(current_user: Annotated[Usersout_Pydantic, Security(get_current_user, scopes=["profile:self"])]):
    logger.debug("Current user: {}".format(current_user))
    return [{"item_id": "Foo"}]

The oauth2 util library

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={
        "profile:read": "Read profile",
        "profile:write": "Write profile",
        "profile:delete": "Delete profile",
        "profile:self": "Retrieve your own profile"
    }
)

async def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme)):
    logger.debug("Security scopes: {}".format(security_scopes))
    logger.debug("Token: {}".format(token))
    if security_scopes.scopes:
        authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
    else:
        authenticate_value = "Bearer"
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": authenticate_value},
    )
    try:
        logger.debug("Decoding Token: {}".format(token))
        payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
        logger.debug("Decoded Token: {}".format(payload))
        email: str = payload.get("email")
        logger.debug("Email from decoded token: {}".format(email))
        if email is None:
            raise credentials_exception
        token_scopes = payload.get("scopes", [])
    except (JWTError, ValidationError):
        raise credentials_exception
    logger.debug("Token scopes from decoded token: {}".format(token_scopes))
    user: Users = await Users.get(email=email)
    if user is None:
        raise credentials_exception
    for scope in security_scopes.scopes:
        if scope not in token_scopes:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Not enough permissions",
                headers={"WWW-Authenticate": authenticate_value},
            )
    return Usersout_Pydantic.from_tortoise_orm(user)

The user model

import uuid
from typing import Optional

from pydantic import BaseModel
from tortoise import fields, Model
from tortoise.contrib.pydantic import pydantic_model_creator


class Users(Model):
    """
    This class represents a user, and defines the attributes that are stored in the database.
    """

    # The unique ID for this user (generated using the uuid module)
    id = fields.UUIDField(pk=True, default=uuid.uuid4)

    # The email for this user
    email = fields.CharField(max_length=64, unique=True, index=True)

    # The username for this user
    username = fields.CharField(max_length=64, unique=True, null=True)

    # The password for this user
    password = fields.CharField(max_length=64)

    # The type of user this is
    type = fields.CharField(max_length=64, default="BASIC")

    # The timestamp for when this user was added to the database
    created_at = fields.DatetimeField(auto_now_add=True)

    # The timestamp for when this user was last updated in the database
    updated = fields.DatetimeField(auto_now=True)

    # The timestamp for when this user was last logged in
    last_login = fields.DatetimeField(null=True)

    # The timestamp for when this user was last logged out
    last_logout = fields.DatetimeField(null=True)

    # The timestamp for when this user was last deleted
    last_deleted = fields.DatetimeField(null=True)


Usersin_Pydantic = pydantic_model_creator(Users, name="User", exclude_readonly=True)
Usersout_Pydantic = pydantic_model_creator(Users, name="UserOut", exclude=("password", "created_at", "updated"), exclude_readonly=True)

Upon making a GET request to the endpoint I'm getting an error response from FastAPI

plutus-api-1  | INFO:     172.29.0.1:55654 - "GET /api/v1/user/self HTTP/1.1" 422 Unprocessable Entity

I'm using Postman/curl to make the requests (ex. of the curl output for this request)

curl --location --request GET 'https://localhost:8000/api/v1/user/self' \
--header 'Authorization: Bearer REDACTED_TOKEN'

Response

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

This response looks to be expecting some fields from the Userout_Pydantic model. I've also tried creating a UserOut Class utilizing BaseModel from pydantic with all fields being Optional with the same response from FastAPI.

What could I be doing wrong here? Am I overlooking something throughout the docs? Any information would be useful. Thanks


r/FastAPI • • Jan 26 '24

Other Leapcell: Heroku + Airtable Hybrid Alternative for Python

1 Upvotes

Hi, I'm Isaac. I previously shared the first version of Leapcell here, and it received positive feedback. However, due to my less-than-ideal communication skills, both the content and landing process were challenging for users to understand. After engaging with some users, I revised it to the current version, optimizing the landing process.

Leapcell: https://leapcell.io/

Leapcell is an application and database hosting platform, essentially a Heroku + Airtable hybrid. It allows you to deploy code from GitHub, similar to Heroku, with automatic scaling capabilities. Additionally, it features an integrated search engine and BI engine in its database and provides a data management system with an Airtable-like interface. In simple terms, it installs a CMS for Jamstack (supporting various languages). For more details, please refer to Leapcell Documentation.

Our goal is to enable users to focus on specific business implementations, allowing more individuals (Product Managers, Marketing professionals, Data Scientists) to participate in content creation and management without spending too much time on infrastructure and DevOps.

Here's a Fastapi example: https://leapcell.io/issac/fastapi-blog

For documentation on deploying fastapi projects, check this link: https://docs.leapcell.io/docs/application/examples/fastapi

The database link is here, and if you're familiar with spreadsheets, you'll find the interface user-friendly (Python client: leapcell-py): https://leapcell.io/issac/flask-blog/table/tbl1738878922167070720

The deployment process for Django, Flask, and other projects is also straightforward.

Leapcell is currently in beta testing, and we welcome any feedback or questions.


r/FastAPI • • Apr 08 '24

pip package [New package] FastED - make your business objects' instance methods work as dependencies as simply as `Depends(MyClass.make_something)`

1 Upvotes

If you've ever had to write multiple dependencies and a lot of boilerplate just to trigger some functionality on one of your business objects (typically one dependency for creating an instance, one for collecting the arguments of one of its methods, and maybe one more for combining these into the dependency and value you actually need), then you know the inconvenience this small package solves.

The fasted.selfdependent decorator simplifies all of this in a single Depends(MyClass.make_something) declaration. The decorator supports both sync and async instance method and generator dependencies; an optional factory/"dependable" for instance creation; as well as inheritance. And of course decorated methods work as normal if not used as a dependency, and correct typing makes sure mypy won't complain either.

If you're curious, you can check out the docs here.


r/FastAPI • • Jul 20 '24

pip package pycountries lib compatible with pydantic from scratch, supports amount normalization and much more

Thumbnail
self.python
1 Upvotes

r/FastAPI • • Jul 18 '24

Hosting and deployment Fastapi with Google Cloud Functions?

1 Upvotes

Is there any way to (easily) deploy a FastAPI route as a Google Cloud Function? As far as I could grasp from docs, GCF integrate well with Flask, but no so much with FastAPI, and I'd love to be able to leverage FA types, validations and automatic documentation, while not depending on more complex/costly infrastructures such as Google Cloud Run or App Engine.

Thanks for any tips!


r/FastAPI • • Aug 31 '24

Question Semantic Versioning Methods

1 Upvotes

I have gone down the rabbit hole a bit on trying to implement some more professionalism into my self-taught spaghetti of programs, and tried a few methods of implementing a semantic version handling (link for further reading on the topic -> semver.org) to ensure my endpoints are able to be called with/without a version number and effectively handle the route logic as I make changes.

I started by trying to create a dynamic route which would add the route to a dictionary and then the correct function for the route would be called once parsed. However this kept returning an error due to the dict object not being callable. Code below, if anyone wants to take a shot at getting it to work, I have pulled these from old versions but may not be exactly the same time so there might be some glaringly obvious differences in the 2, but the method was along these lines... it was basically intended to do the same as the below working code will do but keeping things a bit cleaner as each route would have router endpoints and multiple async functions and just return whichever is the right one to use.

-- Not working code --

External route versioning file

from fastapi import Request, HTTPException
from fastapi.routing import APIRoute
from packaging import version
from typing import Callable, Dict
from app.utils.logger import logger

# Create a shared dictionary for all routes
shared_version_handlers: Dict[str, Dict] = {}

class VersionedAPIRoute(APIRoute):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @classmethod
    def add_version_handler(cls, introduced: str, deprecated: str | None, handler: Callable):
        logger.info("Adding version handler: introduced=%s, deprecated=%s", introduced, deprecated)
        shared_version_handlers[introduced] = {
            'handler': handler,
            'introduced': version.parse(introduced),
            'deprecated': version.parse(deprecated) if deprecated else None
        }
        logger.info("Registered version handlers: %s", shared_version_handlers)

    def get_route_handler(self):
        async def versioned_route_handler(request: Request):
            api_version_str = request.headers.get("api-version")
            logger.info("API version header: %s", api_version_str)
            logger.info("Registered version handlers: %s", len(shared_version_handlers))

            if not api_version_str:
                logger.info("No API version header found")
                non_deprecated_versions = [
                    v for v, info in shared_version_handlers.items() if not info['deprecated']
                ]
                logger.info("Non-deprecated versions available: %s", non_deprecated_versions)
                if not non_deprecated_versions:
                    logger.info("No non-deprecated API version available")
                    raise HTTPException(status_code=400, detail="No non-deprecated API version available")
                latest_version = max(non_deprecated_versions, key=version.parse)
                return await shared_version_handlers[latest_version]['handler'](request)

            try:
                api_version = version.parse(api_version_str)
            except version.InvalidVersion:
                logger.info("Invalid API version")
                raise HTTPException(status_code=400, detail="Invalid API version")

            compatible_versions = [
                v for v, info in shared_version_handlers.items()
                if info['introduced'] <= api_version and (info['deprecated'] is None or api_version < info['deprecated'])
            ]

            logger.info("Compatible versions found: %s", compatible_versions)
            if not compatible_versions:
                logger.info("No compatible API version found")
                raise HTTPException(status_code=400, detail="No compatible API version found")

            # Use the latest compatible version
            latest_compatible = max(compatible_versions, key=version.parse)
            return await shared_version_handlers[latest_compatible]['handler'](request)

        return versioned_route_handler

def versioned_api_route(introduced: str, deprecated: str = None):
    def decorator(func):
        func.introduced = introduced
        func.deprecated = deprecated
        return func
    return decorator

Route file layout

from fastapi import APIRouter, Header, HTTPException, Depends
from typing import Optional
import json
from app.routers.external.versioning import versioned_api_route, VersionedAPIRoute

books = json.load(open("app/static/books.json"))

router = APIRouter()
router.route_class = VersionedAPIRoute

def get_api_version(api_version: Optional[str] = Header(None)):
    if api_version is None:
        raise HTTPException(status_code=400, detail="API version header missing")
    return api_version

@router.get("/book_count")
@versioned_api_route(introduced="1.0.0", deprecated="1.0.1")
async def get_book_count_v1(api_version: str = Depends(get_api_version)):
    return {"count": len(books), "api_version": "1.0.0"}

@versioned_api_route(introduced="1.0.1")
async def get_book_count_v1_1(api_version: str = Depends(get_api_version)):
    count = len(books)
    return {"message": "Success", "count": count, "api_version": "1.0.1"}

@versioned_api_route(introduced="1.0.2")
async def get_book_count_v1_2(api_version: str = Depends(get_api_version)):
    count = len(books)
    return {"message": "Success", "data": {"count": count}, "api_version": "1.0.2"}

# Register version handlers
for route in router.routes:
    if isinstance(route, VersionedAPIRoute):
        route.add_version_handler(
            introduced=route.endpoint.introduced,
            deprecated=getattr(route.endpoint, 'deprecated', None),
            handler=route.endpoint
        )

-- End of not working code --

I have instead opted to use a switch case style of logic in each route (so there is only one endpoint to be handled) and each case will have the different logic for the version. Below is a brief example of one route, and the handler function that will be called at the start of each route to reduce repetitive code in each route (as I can see the routes will grow with each additional version by the previous version +/- new changes and won't decrease in size (unless depreciated versions are removed from the route). I think to neaten it up a bit logic inside of the route once the version has been determined could be in a separate function, which would enable the route itself to not end up very large and hard to read (it would somewhat become more of a list of version of the route that can point you to the correct function for that logic version?)

Any further suggestions on how to improve this? or have I missed a feature which is already available which does exactly this?

FWIW - I am not a software engineer, I am an electrical engineer but I like to dabble 😅

-- "Working" code --

from fastapi import APIRouter, HTTPException, Depends, Request
from typing import Optional
from packaging.version import parse
import json
from app.routers.external.versioning import versioned_api_route, get_api_version
from app.utils.logger import logger

books = json.load(open("app/static/books.json"))

router = APIRouter()

def handle_version_logic(api_version: str, introduced: str, deprecated: Optional[str] = None) -> tuple[str, Optional[str], Optional[int]]:
    """
    Handle version logic and return the version type, pre-release type, and pre-release number.
    
    :param api_version: The API version requested.
    :param introduced: The version when the API was introduced.
    :param deprecated: The version when the API was deprecated, if applicable.
    :return: A tuple containing the base version, pre-release type, and pre-release number.
    """
    api_version_req = parse(api_version)
    introduced_version = parse(introduced)
    deprecated_version = parse(deprecated) if deprecated else None
    
    # Check if the requested version is valid
    if api_version_req < introduced_version:
        raise HTTPException(status_code=400, detail="API version not supported")
    
    if deprecated_version and api_version_req <= deprecated_version:
        raise HTTPException(status_code=400, detail="API version is deprecated")

    # Extract pre-release information
    pre_type = None
    pre_number = None
    if api_version_req.pre is not None:
        pre_type = api_version_req.pre[0]
        pre_number = api_version_req.pre[1] if api_version_req.pre[1] != 0 else None

    # Return the base version, pre-release type, and pre-release number
    return str(api_version_req.base_version), pre_type, pre_number

@router.get("/book_count")
@versioned_api_route(introduced="1.0.0", deprecated="1.0.1")
async def get_book_count(request: Request, api_version: str = Depends(get_api_version)):
    
    base_version = None
    pre_type = None
    pre_number = None
    
    if api_version != None:
        base_version, pre_type, pre_number = handle_version_logic(api_version, get_book_count.introduced, get_book_count.deprecated)
    
    # Handle pre-release versions
    if pre_type is not None:
        # Logic for specific pre-release versions
        if pre_type == 'a':
            # If no specific pre-release number is provided, assume the latest
            if pre_number == None:
                # Logic for the latest alpha version
                logger.info("Latest Alpha version logic")
                
                return {"message": "Latest Alpha version logic", "api_version": base_version}
            elif pre_number == 1:
                return {"message": f"Alpha version {pre_number} logic", "api_version": base_version}
            else:
                pass
        elif pre_type == 'b':
            if pre_number == None:
                return {"message": "Latest Beta version logic", "api_version": base_version}
            elif pre_number == 1:
                return {"message": f"Beta version {pre_number} logic", "api_version": base_version}
            else:
                pass
        elif pre_type == 'rc':
            if pre_number == None:
                return {"message": "Latest Release Candidate logic", "api_version": base_version}
            elif pre_number == 1:
                return {"message": f"Release candidate {pre_number} logic", "api_version": base_version}
            else:
                pass
        else:
            raise HTTPException(status_code=400, detail="Invalid pre-release version")
        raise HTTPException(status_code=400, detail="Invalid pre-release version")

    # Switch-case style logic to handle release versions
    if base_version == parse("1.0.0").base_version:
        return {"count": len(books), "api_version": "1.0.0"}
    elif base_version == parse("1.0.1").base_version:
        count = len(books)
        return {"message": "Success", "count": count, "api_version": "1.0.1"}
    elif base_version == parse("1.0.2").base_version or base_version == None:
        count = len(books)
        return {"message": "Success", "data": {"count": count}, "api_version": "1.0.2"}
    else:
        raise HTTPException(status_code=400, detail="Invalid API version")

-- End of working code --


r/FastAPI • • Jan 02 '24

Question Facing difficulty on starting multiple services together

1 Upvotes

Hi,
I have created 10 microservices using fastapi where all of them are connected to an api-gateway.

Now the issue is that I am having hard time starting all of the services together. I can use docker to compose up and start them, but is there any other way to start all of the services using a batch/sh/command or anything else apart from starting all of the apps one by one?


r/FastAPI • • Aug 18 '24

Question New user - response validation error

1 Upvotes

Apologies for what is almost certainly an incredibly basic issue, but I've been butting my head against it for hours and can't figure out what the problem is.

I am trying to adapt the SQL Database documentation app to a very basic Todo app. Seems to be one of those so simple problems that googling isn't helping. I can tell it's an issue between the API call and the Pydantic model, but I can't see anything that's causing it.

database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

schemas.py

from pydantic import BaseModel

class ToDo(BaseModel):
    id: int
    text: str
    isComplete: bool = False

models.py

from sqlalchemy import Boolean, Column, Integer, String
from .database import Base

class ToDo(Base):
    __tablename__= 'todos'

    id = Column(Integer, primary_key=True)
    text = Column(String, index=True)
    isComplete = Column(Boolean, default=False)

crud.py

from sqlalchemy.orm import Session
from . import models, schemas

def add_todo(db: Session, todo: schemas.ToDo):
    db_todo = models.ToDo(id=todo.id, text=todo.text, isComplete=todo.isComplete)
    db.add(db_todo)
    db.commit()
    db.refresh(db_todo)
    return db_todo

def mark_complete(db: Session, todo_id: str):
    db_todo = db.query(models.ToDo).filter(models.ToDo.id == todo_id).first()
    if db_todo:
        db_todo.isComplete = True
        db.commit()
        db.refresh(db_todo)
    return db_todo

def get_todos(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.ToDo).offset(skip).limit(lim

main.py

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/todos/", response_model=schemas.ToDo)
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    todos = crud.get_todos(db, skip=skip, limit=limit)
    return todos

@app.post("/todos/post/", response_model=schemas.ToDo)
def create_todo(todo: schemas.ToDo, db: Session = Depends(get_db)):
    return crud.add_todo(db, todo=todo)

@app.patch("/todos/{todo_id}/complete", response_model=schemas.ToDo)
def mark_complete(todo_id: str, db: Session = Depends(get_db)):
    return crud.mark_complete(db, todo_id=todo_id)

Curl

curl -X http://localhost:8000/todos/

Error

fastapi.exceptions.ResponseValidationError: 1 validation errors:

{'type': 'model_attributes_type', 'loc': ('response',), 'msg': 'Input should be a valid dictionary or object to extract fields from', 'input': []}


r/FastAPI • • May 31 '24

Question Can’t display invalid credentials message

Thumbnail
gallery
1 Upvotes

Hi guys, I don’t know why when the user fails to login, my login page won’t display “Invalid credentials, try again.”, but if the user succeeds to login, it can successfully redirect to my index page.

Can someone help me please🙏


r/FastAPI • • Dec 30 '23

Question return RSA public_key to encrypt login data (help)

1 Upvotes

Hello!
I have a login API using HTTP and I want to create a unique RS256 key pair to encrypt/decrypt the data in the header, just for the login process.
I already can create, store and read the keys but I don't know how to send the public one to the client so they could use it to encrypt the username:password,
Should I send the .pem? string? the binary? JTW?
Is it stupid? or just I must use SSL and HTTPS like the right children of god?
The passwords are already hashed and salted tho.

I'm new in security, don't burn me
(it's a local server in a WLAN, eventually it will be hosted but IDK)


r/FastAPI • • Jul 15 '24

Question model seemingly loads again despite being loaded on startup with @app.on_event("startup")

1 Upvotes

I'm trying to create an API which performs function on an input

from .main import main

@app.on_event("startup")
async def startup_event():
    start_time = time.time()
    app.state.model = SentenceTransformer('model')
    end_time = time.time()
    logger.info(f'Models loaded in {end_time - start_time} seconds')

@app.post("/search")
async def search(
    question: str = Form(...),
) -> JSONResponse:
    logger.info(f'question----> :{question}')

    model = app.state.model 

    start_time_main = time.time()
    results, lookup_time = await main(query=question, model=model)

    end_time_main = time.time()
    logger.info(f'Main func in {end_time_main - start_time_main} seconds')

    api_results = [
        {
            "answer": result[1],
        }
        for result in results
    ]
    
    return JSONResponse(content=api_results)

To run my server, i'm using  uvicorn backend.main:app --reload --port 8000 --log-level debug the Logs are:

INFO:backend.apis:Models loaded in 8.509195804595947 seconds
INFO:     Application startup complete.
INFO:backend.apis:question----> :How to get ticket
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00,  1.25it/s]
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 27.80it/s]
INFO:backend.apis:Main func in 13.68946623802185 seconds
INFO:     127.0.0.1:35428 - "POST /lookup?search=How%20to%20get%20ticket HTTP/1.1" 200 OK

Search time is under 2 milliseconds. Earlier, the API latency was under 2 sec, but today after few edits again it is taking 5-10 s to work. I believe the model itself is being loaded again and again on every API search and that is why the API latency is over 5-10s

I already tried reloading the server,text editor, and postman clients on (POST request). But it isn't working. I also edited the startup function but no result is coming


r/FastAPI • • Aug 15 '24

Question Is there a FastAPI version of this?

Thumbnail reddit.com
1 Upvotes

r/FastAPI • • May 22 '24

Question NoModuleFoundError in PyCharm

1 Upvotes

Hi, i am a fastApi and python noob, i'm working on a web api and when i go to run it i get the error: shown below in the attached image.

The project structure is also attached in the second image, any help will be greatly appreciated in resolving this blocker.


r/FastAPI • • Jun 22 '24

Question Help!!!

1 Upvotes

Im a finance grad, I used to do web dev as a side gig. So im a rookie, I have had some previous experience with fastapi and flask. But im thinking of making a car rental app, can you please help me with some guidance, im thinking flutter could a good option but unfortunately i haven't tried it yet, i had some decent experience with react js but not so sure how similiar it is to react native. Can i get some suggestions


r/FastAPI • • Apr 08 '24

Question Redirect stdout to FastAPI websocket.

1 Upvotes

Hi, I'm building an application where I'm using library functions. Some of those library functions uses print statement in them. I wanted to redirect all those stdout to my frontend using the WebSocket. Python base socket class have a makefile function that makes the socket a file like object but couldn't find any way around fastapi websocket.