Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

One Request, Two Answers: the Same Post as an HTML Page and as JSON

Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Compare an HTML response and a JSON response for the same data by status, content type and size
  • Trace the page path (view and template) and the API path (view set and serializer)
  • Explain who builds the page in each case, and why a separate front end needs JSON
  • Explain why the API answers HTML to a browser and JSON with ?format=json

Before you start

  • Backend vs frontend basics
  • HTTP requests, status codes and headers

Remember the restaurant: the kitchen is the back end, the dining room is the front end (see backend vs frontend). Our blog's kitchen can answer in two ways. It can cook and plate everything, so the waiter carries out a finished plate. Or it can hand over the prepared ingredients, and the dining room plates them itself.

The plated dish is an HTML page. The ingredients are JSON. In this article we ask the Django blog for the same post twice and compare the two answers. The post is number 6, Getting Started with Machine Learning, on Django 6.1.3 with SQLite.

Answer one: the page

The page lives at /post/getting-started-with-machine-learning/. In urls.py, that path goes to post_detail in views.py:

path('post/<slug:slug>/', views.post_detail, name='post_detail'),
def post_detail(request, slug):
    """Individual post detail page with comments"""
    post = get_object_or_404(Post, slug=slug, status='published')
    comments = post.comments.filter(approved=True)
    ...
    return render(request, 'blog/post_detail.html', {
        'post': post,
        'comments': comments,
        'comment_form': comment_form
    })

The view gets the post by its slug, the model reads it from SQLite, and render fills post_detail.html: the title, the category and the content drop into their places. The server sends back one finished page. The kitchen did all the plating.

The server log line:

[date time] "GET /post/getting-started-with-machine-learning/ HTTP/1.1" 200 12731

Status 200, content type text/html; charset=utf-8, 12,731 bytes, and a Vary: Cookie header. The first lines of the body:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Getting Started with Machine Learning - Elegant Blog</title>

The title tag already holds the post's title. Everything is in there: header, layout, text, and links to the style sheets. The browser didn't put the page together. It only drew what the server made.

Answer two: the JSON

The same post from the API is at /api/posts/6/. In api_urls.py the router sends posts to PostViewSet, and because we're asking for one post, get_serializer_class picks PostDetailSerializer:

class PostViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticatedOrReadOnly]
    ...
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return PostDetailSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return PostCreateUpdateSerializer
        return PostListSerializer
class PostDetailSerializer(serializers.ModelSerializer):
    """Serializer for Post detail view"""
    author = UserSerializer(read_only=True)
    comments = CommentSerializer(many=True, read_only=True)
    comments_count = serializers.SerializerMethodField()
    read_time = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = [
            'id', 'title', 'slug', 'author', 'content', 'excerpt', 'category',
            'created_at', 'updated_at', 'status', 'comments', 'comments_count', 'read_time'
        ]

The model reads the same row from the same database. The serializer turns it into JSON with the 13 fields listed in Meta. No template this time; the kitchen hands over the ingredients.

[date time] "GET /api/posts/6/ HTTP/1.1" 200 2976

Status 200 again, but the content type is application/json, 2,976 bytes, with Vary: Accept, Cookie and Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS. Some of the fields, pretty-printed:

{
  "id": 6,
  "title": "Getting Started with Machine Learning",
  "slug": "getting-started-with-machine-learning",
  "category": "Technology",
  "status": "published",
  "comments_count": 0,
  "read_time": "1 min read"
}

Only data. No layout, no header, no styles. Something else has to turn this into a page.

Side by side

PageJSON
Address/post/getting-started-with-machine-learning//api/posts/6/
Status200200
Content-Typetext/html; charset=utf-8application/json
Size12,731 bytes2,976 bytes
Built bythe view and a templatethe view set and a serializer
Allow headernoneGET, PUT, PATCH, DELETE, HEAD, OPTIONS

Both carry the same post content. The page is about 4.3 times bigger because it carries the whole layout. The Allow header lists the methods this address supports, though writing still needs a login.

Who builds the page

Top lane: the server runs the template and sends a finished HTML page; the browser only draws it. Bottom lane: the server sends JSON; JavaScript in the browser, often React, fetches it and fills the page itself. HTML answer: the server plates the dish Server view + template finished page text/html Browser only draws it JSON answer: the dining room plates it Server view set + serializer data application/json Browser JS builds the page
Either way the user sees a post. What changes is where the plating happens.

With the HTML answer, the server builds the page: the template runs in the kitchen and the finished page goes to the browser. With the JSON answer, the browser builds it: JavaScript running in the page fetches the JSON, then puts the title, the category and the content into the page itself. That JavaScript is the front end of a full-stack app, often built with something like React.

The API, asked like a browser

Open /api/posts/6/ straight in your browser and you get a page, not plain JSON. A browser says in its Accept header that it prefers HTML. Django REST framework sees that and wraps the JSON in a page it builds for people:

RequestContent-TypeBytes
/api/posts/6/ from a browsertext/html; charset=utf-810,143
/api/posts/6/?format=jsonapplication/json2,976

That's why the API's Vary header lists Accept: the answer depends on what the caller asks for.

What this means for full stack

In a full-stack app the back end stops building pages and answers with JSON. /api/posts/ already returns all six posts in one answer, with the keys count, next, previous and results (3,114 bytes). A web front end reads that JSON, and a phone app can read the same JSON. One back end, many front ends. If you're building the API side in FastAPI, the response shape is designed with models, as in FastAPI request and response models.

Trust stays on the server

One thing doesn't change, whichever answer you use. PostViewSet sets IsAuthenticatedOrReadOnly: anyone can read posts, but writing needs a login. A POST to /api/posts/ without logging in:

[date time] "POST /api/posts/ HTTP/1.1" 403 58

The body is JSON:

{"detail":"Authentication credentials were not provided."}

And the page side agrees: /admin/ without a login is a 302 to /admin/login/?next=/admin/. Whether the kitchen plates the dish or hands over the ingredients, the kitchen decides who gets served.

Common mistakes

  • Judging an API by what the browser shows. The browsable page is DRF being helpful; check the Content-Type, or add ?format=json.
  • Thinking JSON means less security work. The server still checks every write.
  • Assuming the page and the API share a template. The page uses a template; the API uses a serializer, and its fields are set in Meta.fields.

Quick recap

Page answerJSON answer
Content typetext/htmlapplication/json
Who plates itthe server's templatecode in the browser
Who reads ita person, in a browsera web front end, a phone app, other services
Who checks writesthe serverthe server

Try it yourself

Run your blog, open a post's page, then open the same post under /api/posts/ in the browser, and once more with ?format=json. Compare the Content-Type of all three in the browser's network tab.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 5 of 26

Previous
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
Next post
What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

FastAPI Hello World: Routes, uvicorn and the Free Swagger Page

The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.

RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes

An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • Answer one: the page
  • Answer two: the JSON
  • Side by side
  • Who builds the page
  • The API, asked like a browser
  • What this means for full stack
  • Trust stays on the server
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.