
Swagger UI ?? FastAPI? JSON ??? ??
FastAPI? ??? ? Swagger UI ?? JSON ???? ???? ???? ??? ???? ?????. Swagger UI? ?????. ? ?? ??? ???? ??? URL? ?? ???? ?? ???? ?????? ??? ??? ? ????.
Javascript ????? ??
?? ????? JSON ???? ???? ??? ? ?? Fetch API? ?? Javascript ????????. ?? ?? ?? ?????.
<code class="javascript">body: JSON.stringify({name: "foo", roll: 1})</code>
? ?? ??? ??? ?? Javascript ??? JSON?? ?????.
????? ??
FastAPI ?????? ?? ?? ? ??? ??? ? ????.
-
Jinja2Templates: ? ???? ??? ??? ?? ??? ??? HTML/JS ???? ????? ??? ?????. ?? ?? ?? ???? JSON?? ??? ? ????.
-
JSON ?? ??: Fetch API? ???? ??? ???? ??? JSON ???? ?? ??? ? ????.
?? ?
Python?? ?? ?? ?? ?????.
app.py
<code class="python">from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class Item(BaseModel):
name: str
roll: int
@app.post("/")
async def create_item(item: Item):
return item
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})</code>
template/index.html
<code class="html"><!DOCTYPE html>
<html>
<body>
<h1>Post JSON Data</h1>
<form method="post" id="myForm">
name : <input type="text" name="name" value="foo">
roll : <input type="number" name="roll" value="1">
<input type="button" value="Submit" onclick="submitForm()">
</form>
<div id="responseArea"></div>
<script>
function submitForm() {
var formElement = document.getElementById('myForm');
var data = new FormData(formElement);
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(Object.fromEntries(data))
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("responseArea").innerHTML = data;
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html></code>
? ??? ??? Swagger UI ??? JSON ???? FastAPI ???? ????? ??? ? ????. ? ?? ??? ???? ??? URL? ?? ? ? ???? ????? ???? ?? ??? ?????.
? ??? Swagger UI ?? FastAPI? JSON ???? ???? ??? ??????? ?? ?????. ??? ??? PHP ??? ????? ?? ?? ??? ?????!