Last active
October 25, 2024 08:21
-
-
Save baobuiquang/0c3328be740ebdaf23f805308b398f8a to your computer and use it in GitHub Desktop.
FastAPI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Full boilerplate project: https://github.com/baobuiquang/fastapi | |
# How to POST request: | |
# Invoke-RestMethod -Uri http://127.0.0.1:8888/post -Method POST | |
from fastapi.middleware.cors import CORSMiddleware | |
from fastapi import FastAPI | |
import uvicorn | |
import _config | |
app = FastAPI() | |
origins = ["*"] | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=origins, | |
allow_credentials=True, | |
allow_methods=["*"], | |
allow_headers=["*"], | |
) | |
# Method 1: Can handle string contains "/" character | |
# > http://localhost:8888/path_1/?input_text_1=TYPE_INPUT_HERE_1 | |
@app.get("/path_1/") | |
def booooo_1(input_text_1: str = "DEFAULT_TEXT_1"): | |
return { | |
"message_1": f"Hello {input_text_1}!" | |
} | |
# Method 2: Shorter URL, variable name not matter | |
# > http://localhost:8888/path_2/TYPE_INPUT_HERE_2 | |
@app.get("/path_2/{input_text_2}") | |
def booooo_2(input_text_2: str = "DEFAULT_TEXT_2"): | |
return { | |
"message_2": f"Hello {input_text_2}!" | |
} | |
if _config.IS_DEVELOPING == False: | |
uvicorn.run( | |
app, | |
host = _config.API_HOST, | |
port = _config.API_PORT, | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# How to POST request: | |
# Invoke-RestMethod -Uri http://127.0.0.1:8888/post -Method POST | |
from fastapi import FastAPI | |
app = FastAPI() | |
# Initialize the variable | |
myvar = False | |
# GET | |
@app.get("/get") | |
async def get_myvar(): | |
return {"myvar": myvar} | |
# POST: Invoke-RestMethod -Uri http://127.0.0.1:8888/post -Method POST | |
@app.post("/post") | |
async def toggle_myvar(): | |
global myvar | |
myvar = not myvar | |
return {"myvar": myvar} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment