When working with FastAPI, it's possible to post JSON data without the intermediary of the Swagger UI. Here's how to achieve this:
Employ a JavaScript-based interface like the Fetch API to send data in JSON format. Here's an example:
<code class="javascript">var data = { name: "foo", roll: 1 } fetch('/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(resp => { return resp.text(); }).then(data => { // Handle the response });</code>
Alternatively, you can utilize Jinja2 Templates and an HTML form to submit your data. Here's how:
<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>
<code class="html"><form method="post"> <input type="text" name="name" value="foo"> <input type="number" name="roll" value="1"> <input type="submit" value="Submit"> </form> <div id="responseArea"></div> <script> document.querySelector('form').addEventListener('submit', (event) => { event.preventDefault(); var data = new FormData(event.target); fetch('/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(Object.fromEntries(data)) }).then(resp => { return resp.text(); }).then(data => { document.getElementById("responseArea").innerHTML = data; }).catch(error => { console.error(error); }); }); </script></code>
By using these techniques, you can conveniently post JSON data to your FastAPI backend without relying on the Swagger UI interface.
The above is the detailed content of How to Submit JSON Data to FastAPI without Swagger UI?. For more information, please follow other related articles on the PHP Chinese website!