Hi ππ
Welcome to a new post, Today I will share with you How to send JSON data to FastAPI using Javascript.
step 1
Create login.html page
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/daisyui/3.7.5/full.css" integrity="sha512-Lr5WBlKu2mm4qy5sAEaqC/61YBq2Yyxk8YdlgX+HMvIBSS4v+OP6BLf7d3lEF4lSUdiw0uZHLagpgOicVSMs4g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="form">
<input
id="username"
type="text"
placeholder="usernme"
class="input input-bordered input-info w-full max-w-xs" />
<input
id="password"
type="password"
placeholder="password"
class="input input-bordered input-info w-full max-w-xs" />
<button id="bt" class="btn btn-info">login</button>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script>
async function send_data(username, password) {
fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
'username': username.val(),
'password': password.val()
})
})
.then(resp => resp.json()) // or, resp.text(), etc
.then(data => {
console.log(data); // handle response data
})
.catch(error => {
console.error(error);
});
}
let bt = $('#bt')
bt.click(function () {
let usernme = $('#username')
let password = $('#password')
send_data(usernme, password)
})
</script>
<style>
.form {
display: flex;
flex-direction: column;
gap: 31px;
width: 400px;
padding: 20px;
margin: 100px auto;
}
</style>
daisyui daisyUI is a plugin for Tailwind CSS
step 2
Create login page route and login page post route
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get('/login')
def logIn():
return HTMLResponse(open('login.html', 'r').read())
@app.post('/login')
async def login(request : Request):
json = await request.json()
return json
result
Now we're done π€
Don't forget to like and follow π
Support me on PayPal π€
https://www.paypal.com/paypalme/amr396
Top comments (0)