To build a simple FastAPI application that fetches data from a MySQL database and integrates with an Apache HTTP server, you need to write both the FastAPI code and an Apache configuration file to route requests to the FastAPI app. Below, I'll provide the necessary code and configuration steps.
FastAPI Application Code
First, you'll need to ensure you have the required packages installed. You can do this by running:
pip install fastapi uvicorn sqlalchemy mysql-connector-python
Now, here is the FastAPI application code:
from fastapi import FastAPI, HTTPException
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
DATABASE_URL = "mysql+mysqlconnector://user:password@localhost/db1" # Replace with your actual MySQL credentials
Base = declarative_base()
class Demotab1(Base):
__tablename__ = "demotab1"
id = Column(Integer, primary_key=True, index=True)
person = Column(String(255), index=True)
salary = Column(Float)
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/get_salary")
async def get_salary(db: Session = next(get_db())):
persons = db.query(Demotab1).all()
if not persons:
raise HTTPException(status_code=404, detail="No data found")
return [{"person": p.person, "salary": p.salary} for p in persons]
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Replace "user:password" with your actual MySQL username and password.
Apache HTTPD Configuration
To pass requests to your FastAPI application, you'll need an Apache configuration. This commonly involves using a reverse proxy with mod_proxy and mod_proxy_http.
Ensure Apache has these modules enabled:
a2enmod proxy
a2enmod proxy_http
Now configure Apache to redirect requests to your FastAPI application (add this to your site configuration, often located in /etc/apache2/sites-available/your-site.conf):
<VirtualHost *:80>
ServerName yourdomain.com # Replace with your own domain
ProxyPreserveHost On
ProxyPass /api http://127.0.0.1:8000
ProxyPassReverse /api http://127.0.0.1:8000
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
In this configuration, requests to http://yourdomain.com/api will be forwarded to your FastAPI app running on localhost port 8000.
Run the Application
To start the FastAPI app, run:
uvicorn your_fastapi_file:app --host 127.0.0.1 --port 8000
Make sure to replace your_fastapi_file with the name of the Python file containing your FastAPI app.
Final Steps
After adding the Apache configuration, restart Apache to apply the changes:
sudo systemctl restart apache2
With these configurations, requests to /api/get_salary on your server's domain should be correctly routed to your FastAPI application. The app queries your MySQL database and returns the required data, showcasing all persons and their salaries.