How to use the fastapi.HTTPException function in fastapi

To help you get started, we’ve selected a few fastapi examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github tiangolo / fastapi / docs / src / dependencies / tutorial006.py View on Github external
async def verify_key(x_key: str = Header(...)):
    if x_key != "fake-super-secret-key":
        raise HTTPException(status_code=400, detail="X-Key header invalid")
    return x_key
github mlrun / mlrun / mlrun / api / api / utils.py View on Github external
def log_and_raise(status=HTTPStatus.BAD_REQUEST, **kw):
    logger.error(str(kw))
    raise HTTPException(status_code=status, detail=kw)
github MrNaif2018 / bitcart / api / utils.py View on Github external
authenticate_value = f"Bearer"
        token: str = await oauth2_scheme(request) if not self.token else self.token
        data = (
            await models.User.join(models.Token)
            .select(models.Token.id == token)
            .gino.load((models.User, models.Token))
            .first()
        )
        if data is None:
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="Could not validate credentials",
                headers={"WWW-Authenticate": authenticate_value},
            )
        user, token = data  # first validate data, then unpack
        forbidden_exception = HTTPException(
            status_code=HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
            headers={"WWW-Authenticate": authenticate_value},
        )
        if "full_control" not in token.permissions:
            for scope in security_scopes.scopes:
                if scope not in token.permissions and not check_selective_scopes(
                    request, scope, token
                ):
                    raise forbidden_exception
        if "server_management" in security_scopes.scopes and not user.is_superuser:
            raise forbidden_exception
        if return_token:
            return user, token
        return user
github QwantResearch / idunn / idunn / api / utils.py View on Github external
index_name = PLACE_DEFAULT_INDEX
    elif type not in INDICES:
        raise HTTPException(status_code=400, detail=f"Wrong type parameter: type={type}")
    else:
        index_name = INDICES.get(type)

    try:
        es_places = es.search(
            index=index_name,
            body={"query": {"bool": {"filter": {"term": {"_id": id}}}}},
            ignore_unavailable=True,
            _source_exclude=["boundary"],
        )
    except ElasticsearchException as error:
        logger.warning(f"error with database: {error}")
        raise HTTPException(detail="database issue", status_code=503)

    es_place = es_places.get("hits", {}).get("hits", [])
    if len(es_place) == 0:
        if type is None:
            message = f"place '{id}' not found"
        else:
            message = f"place '{id}' not found with type={type}"
        raise PlaceNotFound(message=message)
    if len(es_place) > 1:
        logger.warning("Got multiple places with id %s", id)

    return es_place[0]
github Gingernaut / microAuth / app / routes / reset_verify.py View on Github external
def get_user_from_token(request: Request, token: str):

    try:
        tokenData = jwt.decode(
            token.replace("__DT__", "."),
            app_config.JWT_SECRET,
            algorithms=[app_config.JWT_ALGORITHM],
        )

        reset = request.state.reset_queries.get_reset_by_id(tokenData["id"])
        if not reset:
            print("no reset for token")
            raise HTTPException(status_code=404)
        elif not reset.isValid:
            print("invalid reset")
            raise HTTPException(status_code=403, detail="Reset token is expired")

        user = request.state.user_queries.get_user_by_id(tokenData["userId"])
        if not user:
            print("no user for token")
            raise HTTPException(status_code=404)
        return user
    except Exception as e:
        log.error(e)
        raise HTTPException(403)
github tiangolo / full-stack-fastapi-postgresql / {{cookiecutter.project_slug}} / backend / app / app / api / api_v1 / endpoints / users.py View on Github external
def create_user(
    *,
    db: Session = Depends(get_db),
    user_in: UserCreate,
    current_user: DBUser = Depends(get_current_active_superuser),
):
    """
    Create new user.
    """
    user = crud.user.get_by_email(db, email=user_in.email)
    if user:
        raise HTTPException(
            status_code=400,
            detail="The user with this username already exists in the system.",
        )
    user = crud.user.create(db, user_in=user_in)
    if config.EMAILS_ENABLED and user_in.email:
        send_new_account_email(
            email_to=user_in.email, username=user_in.email, password=user_in.password
        )
    return user
github Gingernaut / microAuth / app / routes / reset_verify.py View on Github external
def send_reset_email(request: Request, email_address: str):
    user_account = request.state.user_queries.get_user_by_email(email_address)
    if not user_account:
        raise HTTPException(status_code=404)

    reset = request.state.reset_queries.create_reset(user_account.id)

    if request.state.config.API_ENV != "TESTING":
        email.send_reset_email(user_account, reset)

    return {"success": f"reset initiated for account {email_address}"}
github tiangolo / full-stack-fastapi-postgresql / {{cookiecutter.project_slug}} / backend / app / app / api / api_v1 / endpoints / login.py View on Github external
def login_access_token(
    db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
):
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = crud.user.authenticate(
        db, email=form_data.username, password=form_data.password
    )
    if not user:
        raise HTTPException(status_code=400, detail="Incorrect email or password")
    elif not crud.user.is_active(user):
        raise HTTPException(status_code=400, detail="Inactive user")
    access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
    return {
        "access_token": create_access_token(
            data={"user_id": user.id}, expires_delta=access_token_expires
        ),
        "token_type": "bearer",
    }
github MrNaif2018 / bitcart / api / models.py View on Github external
async def create(cls, **kwargs):
        from . import crud

        store_id = kwargs["store_id"]
        kwargs["status"] = "Pending"
        if not store_id:
            raise HTTPException(422, "No store id provided")
        store = await Store.get(store_id)
        if not store:
            raise HTTPException(422, f"Store {store_id} doesn't exist!")
        await crud.get_store(None, None, store, True)
        if not store.wallets:
            raise HTTPException(422, "No wallet linked")
        if not kwargs.get("user_id"):
            kwargs["user_id"] = store.user_id
        kwargs.pop("products", None)
        return await super().create(**kwargs), store.wallets
github QwantResearch / idunn / idunn / api / closest.py View on Github external
def get_closest_place(lat: float, lon: float, es=None):
    if es is None:
        es = get_elasticsearch()
    es_addr = fetch_closest(lat, lon, es=es, max_distance=MAX_DISTANCE_IN_METERS)

    places = {
        "addr": Address,
        "street": Street,
    }
    loader = places.get(es_addr.get("_type"))

    if loader is None:
        logger.warning("Found a place with the wrong type")
        prometheus.exception("FoundPlaceWithWrongType")
        raise HTTPException(
            status_code=404,
            detail="Closest address to '{}:{}' has a wrong type: '{}'".format(
                lat, lon, es_addr.get("_type")
            ),
        )

    return loader(es_addr["_source"])