python
36 lines · 7 steps
Content negotiation in a Flask Blueprint
A single Flask route serves the same article as JSON or HTML based on the client's Accept header.
Explained by
highlit
1from flask import Blueprint, render_template, jsonify, request, abort
2
3from .models import Article
4
5bp = Blueprint("articles", __name__)
6
7
8@bp.route("/articles/<slug>")
9def show(slug):
10 article = Article.query.filter_by(slug=slug, published=True).first()
11 if article is None:
12 abort(404)
13
14 best = request.accept_mimetypes.best_match(
15 ["application/json", "text/html"],
16 default="text/html",
17 )
18
19 if (
20 best == "application/json"
21 and request.accept_mimetypes[best]
22 >= request.accept_mimetypes["text/html"]
23 ):
24 payload = {
25 "slug": article.slug,
26 "title": article.title,
27 "body": article.body,
28 "author": article.author.name,
29 "published_at": article.published_at.isoformat(),
30 "tags": [tag.name for tag in article.tags],
31 }
32 response = jsonify(payload)
33 response.headers["Vary"] = "Accept"
34 return response
35
36 return render_template("articles/show.html", article=article), 200, {"Vary": "Accept"}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1One endpoint can serve multiple representations by inspecting the Accept header instead of splitting into separate URLs.
- 2Setting the Vary header tells caches that responses differ by request headers, preventing wrong cached formats.
- 3Guarding queries with published=True and abort(404) keeps unpublished or missing content invisible.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/content-negotiation-in-a-flask-blueprint-explained-python-eac6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.