Skip to content

Running FastAPI on apache2 #3431

@NegassaB

Description

@NegassaB

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Hello all,
I've developed an api using fastapi that will act as a wrapper that receives sms requests and call the sms api to send said sms and now I'm ready to deploy it. This is the code:

import logging

import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fastapi.middleware.trustedhost import TrustedHostMiddleware

import verifier

logging.basicConfig(
    format='%(asctime)s - %(funcName)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

# get logger
logger = logging.getLogger(__name__)


bot_verifier = None


class DataForBot(BaseModel):
    number: str
    msg_txt: str


def get_application():
    app = FastAPI(title='bot_wrapper', version="1.0.0")

    return app


app = get_application()


@app.on_event("startup")
async def startup_event():
    global bot_verifier
    try:
        bot_verifier = await verifier.Verifier.create()
    except Exception as e:
        logger.error(f"exception occured during bot creation -- {e}", exc_info=True)


@app.post('/telegram_sender/')
async def send_telegram_msg(data_for_bot: DataForBot):
    global bot_verifier
    if not bot_verifier:
        bot_verifier = await verifier.Verifier.create()
    else:
        dict_data = data_for_bot.dict()
        try:
            if await bot_verifier.send_via_telegram(dict_data):
                return {'status': "success", 'data': data_for_bot}
            else:
                raise HTTPException(status_code=404, detail="unable to send via telegram, perhaps user has not started the bot")
        except Exception as e:
            logger.error(f"{e}", exc_info=True)
            raise HTTPException(status_code=500, detail="Something went wrong, please contact server admin")

I want to deploy it on apache b/c it's the only thing I can get my hand onto in my country. I'm using python3.8.9 with fastapi version 0.65.2 and apache/2.4.29, but for the life of me I can't get it to work. I've written an apache conf file and enabled that as such:

<VirtualHost *:80>
	ServerName gargarsa.sms.local
	ServerAdmin webmaster@localhost
	ServerAlias gargarsa.sms.local
	
	DocumentRoot /var/www/verify_bot_api/
	ServerAlias gargarsa.sms.local

	<Directory /var/www/verify_bot_api/src/app/>
		Order deny,allow
		Allow from all
	</Directory>

	ErrorLog ${APACHE_LOG_DIR}/gargarsa.sms.local-error.log
	LogLevel debug
	CustomLog ${APACHE_LOG_DIR}/gargarsa.sms.local-access.log combined
</VirtualHost>

but no avail.
I tried running gunicorn via a screen session but I couldn't access it either.
I tried running it programmatically as such but no avail:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

I understand this is a very broad way to ask, but I'm truly stumped.

How do I run an api built using fastapi on Apache?

Thank you for your assistance.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions