Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect FastAPI to frontend HTML

I am developing this project of a simple meme posting website where I take the UserName, caption, Image URL from the user and want to show all the memes on the home page of the website.

I am new to being a full stack developer, I am using FastAPI as backend and went through its documentation. So far I have been able to get the response from the HTML to the server via a Post request, but now I want to store the data in some database and send that data back to the Home page of the website. I tried finding tutorial videos but wasn't able to get the ones which could help me. Any kind of help is appreciated.

Below is some code about how I am performing the current requests.

from fastapi import Request, status, BackgroundTasks
from fastapi.responses import JSONResponse
from tutorial import app,templates
import time
from datetime import datetime
from pydantic import BaseModel
from typing import Optional
class Record(BaseModel):
    name:str
    caption:str
    meme_type: Optional[str] = None
    img_meme:str

@app.post("/")
async def create_record(record: Record):
    background_tasks.add_task(_run_task,record)
    return record

def _run_task(name: str,caption: str,meme_type:str,img_meme: str):
    time.sleep(3)
    with open("memes.txt",mode="a") as file:
        now=datetime.now()
        content=f""" "Name":{name} \nCaption:{caption} \nURL:{img_meme} : now}\n"""
        file.write(content)
like image 480
Savior Avatar asked Jan 25 '26 10:01

Savior


1 Answers

FastAPI documentation has all the answers you need.

I want to store the data in some database

  • SQL Databases - You can use any relational database you want. The documentation has example codes using SQLAlchemy.
  • Async SQL Databases - You can connect to your relational databases using async/await using a third-party package called databases.
  • NoSQL Databases - FastAPI can also be integrated with any NoSQL. The documentation has example codes using Couchbase.

send that data back to the Home page of the website

  • HTMLResponse - If your app is simple and straightforward.
  • Templates - If you need template rendering. The documentation has example codes for Jinja2.
like image 92
phyominh Avatar answered Jan 26 '26 23:01

phyominh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!