r/FastAPI • • Jul 30 '24

Question What are the most helpful tools you use for development?

28 Upvotes

I'm curious what makes your life as a developer much easier and you don't imagine the development process of API without those tools? What parts of the process they enhance?

It may be tools for other technologies from your stack as well, or IDE extension etc. It may be even something obvious for you, but what others may find very functional.

For example, I saw that Redis have desktop GUI, which I don't even know existed. Or perhaps you can't imagine your life without Postman or Warp terminal etc.


r/FastAPI • • Jul 30 '24

Question Need help while deploying FastAPI server in Azure App services

1 Upvotes

When I am trying to run below code in local, it works fine.

params = urllib.parse.quote_plus(
    f'Driver={Driver};'
    f'Server={Server};'
    f'Database={Database};'
    f'Uid=Trabii_BE_GUY;'
    f'Pwd={Pwd};'
    'Encrypt=yes;'
    'TrustServerCertificate=no;'
    'Connection Timeout=30;'
)

# Construct the connection string
conn_str = f'mssql+pyodbc:///?odbc_connect={params}'

engine = create_engine(conn_str)

But when I am trying to deploy using Azure app services it is giving me below error. I have already verified the credentials twice, but don't know what's wrong.

2024-07-30T08:56:12.370094623Z sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('28000', "[28000] [Microsoft][ODBC Driver 18 for SQL Server][SQL Server]Login failed for user 'Trabii_BE_GUY'. (18456) (SQLDriverConnect)")


2024-07-30T08:56:12.370098023Z (Background on this error at: https://sqlalche.me/e/20/rvf5)

r/FastAPI • • Jul 29 '24

Question App with large user base

7 Upvotes

Hi, has anybody here build an app with a large user base? And how is it going? Are your servers expensive?

Thanks for the insights.


r/FastAPI • • Jul 29 '24

Tutorial Highlighting the strength and suitability of FastAPI while building APIs

6 Upvotes

Lately I have been using FastAPI a lot for my API development needs. Several features of FastAPI are highly impressive. These include:

  • Request parsing
  • Input validation
  • Response serialisation
  • Automatic API documentation

I wrote a post highlighting the strengths and suitability of FastAPI for API development and how it compares against Django.

https://levelup.gitconnected.com/why-should-you-switch-to-fastapi-and-how-it-compares-against-django-da6c3d83aefa


r/FastAPI • • Jul 29 '24

Question FastAPI and fabric singleton for DI

4 Upvotes

Hi. I have some problem with DI and FastAPI. I want to use dependency injection for my endpoints and I must send message to Kafka. I have class for factory

class KafkaFactory:

    def __init__(
        self,
        config: KafkaConfig,
        additional_config: dict,
        kafka_type: KafkaType,
        kafka_config_type: KafkaConfigType,
        token_provider: AbstractTokenProvider | None,
    ):
        self._config = config
        self.kafka_type = kafka_type
        self._additional_config = additional_config
        self._kafka_config_type = kafka_config_type
        self.token_provider = token_provider
        self.kafka_config = self.setup_config()
        self.logger = getLogger("Kafka_Accessor")

    def get_producer(self):
        # await self._create_topic(kafka_config)
        return AIOKafkaProducer(**self.kafka_config)

I wrote dependency for creation kafka producer (I use aiokafka)

def create_kafka_factory(custom_token_provider: AsyncCustomTokenProvider = Depends(new_token_provider)):
    kafka_config: KafkaConfig = setup_config().kafka
    additional_config: dict = setup_config().KAFKA_AIOKAFKA_CONFIG
    kafka_factory = KafkaFactory(
        config=kafka_config,
        additional_config=additional_config,
        kafka_type=KafkaType.AIOKAFKA,
        kafka_config_type=KafkaConfigType.PRODUCER,
        token_provider=custom_token_provider,
    )
    return kafka_factory

And then use it for creation producer for send message

async def get_kafka_producer(kafka_factory: KafkaFactory = Depends(create_kafka_factory)):
    producer = kafka_factory.get_producer()
    try:
        yield producer
    finally:
        await producer.flush()

But I got creation of fabric on every request to my API. How correct rewrite my code and use singleton for my fabric?


r/FastAPI • • Jul 26 '24

Tutorial Validate JWTs from Auth0 in FastAPI [tutorial]

20 Upvotes

Hello everyone! Over the past weeks I've been putting together a tutorial on how to implement API authentication and authorization in FastAPI with Auth0. I just finished the last video that explains how to validate the JWTs issued from Auth0 and wanted to share it with you.

Link to the tutorial: https://youtu.be/AtmyC945_no

The code for the tutorial is available on GitHub: https://github.com/abunuwas/short-tutorials/tree/main/fastapi-auth0-authz

The whole process of issuing and validating JWTs from Auth0 is based on standards, and that's the angle in the video. I explain how to inspect a JWT, how to pull the identity provider's OIDC configuration from its well-known endpoint, where to find and how to use the JWKS (JWT signing keys, the public ones in this case), etc.

I've seen and still see many organizations getting this part of the API authorization process wrong, so hopefully this helps some!

There are two videos preceding this tutorial that explain how to configure the Auth0 tenant and how to create the login and authorization flows. I've put together a playlist (https://www.youtube.com/playlist?list=PLZGraXskpvb8JX17hMZoYQRmMr0fo97G6). I'll add a few more videos to this playlist in the future, but I'll move on to other topics in the coming weeks.

Hope you enjoy the tutorial and find it useful!


r/FastAPI • • Jul 25 '24

Question How to SSL secure fastapi app?

11 Upvotes

So we are using and sharing code of a very rudimentary fastapi app with freelance coders and one of them requested SSL encryption of the endpoints. As silly as it may sound, but I haven't done so in the past so I am a bit at a loss. Can someone point me in the direction of how to SSL secure an endpoint or our app?

Thanks!


r/FastAPI • • Jul 25 '24

Question Hello I need some help to set up API.

0 Upvotes

I can't understand how to integrate with other websites through api, can anyone help ? Like where I am getting api documentation with a lot of examples but I can't understand where to place them. Where I need to place codes? Where I will get codes and also where to get postback url and where I need to place postback url? How to display other websites in my website?


r/FastAPI • • Jul 23 '24

Question S3 server simulation in Python

2 Upvotes

I want to implement S3 server using FastAPI and Python. This is my code for signature validation:

async def verify_signature(request: Request):
    try:
        authorization_header = request.headers.get("Authorization")
        amz_date = request.headers.get("x-amz-date")
        if not authorization_header or not amz_date:
            logging.error("Missing authorization or x-amz-date header")
            return False

        logging.debug(f"\n\n=======================================================\n")
        logging.debug(f"Request URL:\n{request.url}")
        logging.debug(f"Authorization Header:\n{authorization_header}")
        logging.debug(f"x-amz-date:\n{amz_date}")

        auth_parts = authorization_header.split(", ")
        credential_part = auth_parts[0]
        signed_headers_part = auth_parts[1]
        signature_part = auth_parts[2]

        credential_scope = (
            credential_part.split(" ")[1].split("Credential=")[1].split("/")[1:]
        )
        credential_scope = "/".join(credential_scope)

        signed_headers = signed_headers_part.split("SignedHeaders=")[-1].split(";")
        provided_signature = signature_part.split("Signature=")[-1]

        logging.debug(f"Signed Headers:\n{signed_headers}")
        logging.debug(f"Credential Scope:\n{credential_scope}")

        headers_dict = {k.lower(): v for k, v in request.headers.items()}
        sorted_headers = {
            k: headers_dict[k] for k in sorted(headers_dict) if k in signed_headers
        }

        logging.debug(f"Headers Dict:\n{headers_dict}")
        logging.debug(f"Sorted Headers:\n{sorted_headers}")

        canonical_uri = request.url.path
        canonical_querystring = request.url.query
        if False and headers_dict.get("x-amz-content-sha256") == "UNSIGNED-PAYLOAD":
            payload_hash = (
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
            )
        else:
            payload_hash = hashlib.sha256(await request.body()).hexdigest()

        sorted_headers["x-amz-content-sha256"] = payload_hash
        canonical_headers = "".join([f"{k}:{v}\n" for k, v in sorted_headers.items()])

        canonical_request = "\n".join(
            [
                request.method,
                canonical_uri,
                canonical_querystring,
                canonical_headers,
                ";".join(signed_headers),
                payload_hash,
            ]
        )

        logging.debug(f"Canonical Request:\n{canonical_request}")

        string_to_sign = "\n".join(
            [
                ALGORITHM,
                amz_date,
                credential_scope,
                hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
            ]
        )

        logging.debug(f"String to Sign:\n{string_to_sign}")

        date_stamp = credential_scope.split("/")[0]
        signing_key = get_signature_key(
            AWS_SECRET_ACCESS_KEY,
            date_stamp,
            AWS_REGION,
            SERVICE,
        )

        signature = hmac.new(
            signing_key, string_to_sign.encode("utf-8"), hashlib.sha256
        ).hexdigest()

        logging.debug(f"Calculated Signature: {signature}")
        logging.debug(f"Provided Signature: {provided_signature}")

        is_valid = provided_signature == signature
        if not is_valid:
            logging.error("Signatures do not match")
        return is_valid

    except Exception as e:
        logging.error(f"Verification failed: {e}")
        return False

I test with this way:

def test():
    from io import BytesIO

    import boto3

    session = boto3.Session(
        AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION
    )
    client = session.client(
        "s3", endpoint_url=ENDPOINT
    )
    f = BytesIO(b"salam2")
    f.seek(0)
    put_res = client.put_object(Bucket="mybucket", Key="myfile2.txt", Body=f)
    print(put_res)
    get_res = client.get_object(Bucket="mybucket", Key="myfile2.txt")
    print(get_res["Body"].read())
    del_res = client.delete_object(Bucket="mybucket", Key="myfile2.txt")
    print(del_res)

The code works correctly for `GET` and `DELETE` requests. But the calculated signature for `PUT` is not matched.
Any help?


r/FastAPI • • Jul 23 '24

Question Why Do Background Tasks Not Work In Websocket Routes

6 Upvotes

Im having an issue with background tasks in FastAPI where when I add a task from a regular HTTP route it works just fine. But when added from a websocket route FastAPI doesn't run the task for some reason.

Source Code: https://github.com/Lif-Platforms/New-Ringer-Server/blob/65-add-push-notifications-support/src/main.py#L527


r/FastAPI • • Jul 22 '24

Question Any production level request stats vs flask ( docker ) on aws fargate or ecz

2 Upvotes

Has anyone deployed fastapi on docker with workers ( uvicorn ).

How does it scale .

Assume minimal processing and db querying.