Create Blog Post
NotesTo add a web page that contains a form, you need two functions, one using GET to display a web page containing a form, and another using POST to process the submitted data.
Order matters in FastAPI: routes are matched in the order they’re added, and a path is matched before its parameters are validated. So the route with the path /blog/create needs to come before /blog/{id}, else /blog/{id} matches first and FastAPI tries to use the word create as a UUID, which fails with a 422 error like this:
{"detail":[{"type":"uuid_parsing","loc":["path","id"],"msg":"Input should be a valid UUID, invalid character: found `r` at 2","input":"create"}]}Alternatively, try to make context paths unique, such as /blog/read/XXX.
Handling forms needs the python-multipart package, which is already installed as part of fastapi[standard].
Add the following function BEFORE the blogpost_get_view function:
@router.get('/blog/create', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_create_get_view(*, request: Request):
context = {
"page": "create"
}
return templates.TemplateResponse(request, 'blog_create.html', {'context': context})Add the corresponding template, which includes the form for adding a blog post:
{% extends "_base.html" %}
{% block content %}
<!-- Page Header -->
<header class="intro-header" style="background-image: url('/static/img/contact-bg.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Create</h1>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Complete the form to add a new blog post:</p>
<form action="/blog/create" method="post">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" id="title" name="title" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Teaser</label>
<input type="text" class="form-control" placeholder="Teaser" id="teaser" name="teaser" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Content</label>
<textarea class="form-control" placeholder="Content" id="content" name="content"
required></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Cover Image</label>
<input type="text" class="form-control" placeholder="Cover Image" id="cover_image"
name="cover_image" required>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Published</label>
<input name="published" id="published" type="checkbox" checked>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<hr>
{% endblock %}The key here is that each <input> HTML tag includes a name="", and the form has <form action="/blog/create" method="post">, so when the form is submitted it will use the POST function at path /blog/create.
Let’s now add that function to handle the POST method, notice the path is the same for both GET & POST, it is the methods defined @router.get and @router.post that count.
Moreover, see how each input to the function correlates to the name of the field in the HTML form. For example title: str = Form(...) comes from name="title" in web/templates/blog_create.html.
@router.post('/blog/create', response_class=HTMLResponse)
def blogpost_create_post_view(*,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: str = Form(...),
published: bool = Form(False),
session: Session = Depends(get_session_db)):
new_blogpost = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image, published=published)
post = create_blogpost_api(blogpost_in=new_blogpost, session=session)
return RedirectResponse(f'/blog/{post.id}', status_code=status.HTTP_303_SEE_OTHER)To recap, the blogpost_create_post_view function takes in the values from the web form, calls the create_blogpost_api function to create the record in the database, and redirects to the new post using RedirectResponse. The three dots in Form(...) mean the field is required.
A few details worth knowing:
- An HTML checkbox is only sent when it’s ticked, and then its value is
on.published: bool = Form(False)handles both cases: Pydantic readsonasTrue, and a missing field falls back toFalse. - The redirect uses
303 See Other, which tells the browser to follow up with a GET. This is the “Post/Redirect/Get” pattern: refreshing the page afterwards doesn’t resubmit the form. (302usually behaves the same in browsers, but303says exactly what’s meant.) - If a required field is missing, FastAPI responds with a
422JSON error before your function runs. The form’srequiredattributes stop that happening in normal use.
Hopefully all that has made sense? There will be a few imports to deal with, so here is the code in web/views/blog_views.py in its entirety at this stage:
import uuid
from fastapi import APIRouter, status, Request, Depends, Form
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlmodel import Session
from api.blog_apis import get_blogpost_by_id_api, create_blogpost_api
from db.db import get_session_db
from db.schemas.blog_schemas import BlogPostIn
router = APIRouter()
templates = Jinja2Templates('web/templates')
@router.get('/blog/create', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_create_get_view(*, request: Request):
context = {
"page": "create"
}
return templates.TemplateResponse(request, 'blog_create.html', {'context': context})
@router.post('/blog/create', response_class=HTMLResponse)
def blogpost_create_post_view(*,
title: str = Form(...),
teaser: str = Form(...),
content: str = Form(...),
cover_image: str = Form(...),
published: bool = Form(False),
session: Session = Depends(get_session_db)):
new_blogpost = BlogPostIn(title=title, teaser=teaser, content=content,
cover_image=cover_image, published=published)
post = create_blogpost_api(blogpost_in=new_blogpost, session=session)
return RedirectResponse(f'/blog/{post.id}', status_code=status.HTTP_303_SEE_OTHER)
@router.get('/blog/{id}', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def blogpost_get_view(*, id: uuid.UUID, request: Request, session: Session = Depends(get_session_db)):
post = get_blogpost_by_id_api(id=id, session=session)
context = {
"page": "blog",
"post": post
}
return templates.TemplateResponse(request, 'blogpost.html', {'context': context})Head to http://localhost:8000/blog/create and you should be able to use the form to add new blog posts. For the cover image, enter a path such as /static/img/post-bg.jpg for now.
The navigation includes a link to /blog/create. Once authentication is added in a later section, it will only be shown (and the page only usable) when you’re logged in.