ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง
อ่านส่วนหัวคำขอและคุกกี้ กำหนดค่าให้กับการตอบกลับ และส่งชนิดการตอบกลับแบบกำหนดเอง เช่น ข้อความธรรมดา HTML การเปลี่ยนเส้นทาง และการสตรีมใน FastAPI
ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Beyond the JSON Body
Request and response handling involves more than the JSON body. Headers and cookies carry metadata like auth tokens, content negotiation, and sessions. FastAPI gives you typed access to both.
Reading a Header
Declare a parameter with Header to read an incoming header. FastAPI auto-converts user_agent to the User-Agent header name.
from fastapi import FastAPI, Header
app = FastAPI()
@app.get('/info')
async def info(user_agent: str = Header(default=None)):
return {'ua': user_agent}Reading Cookies
Use Cookie to read a named cookie, just like headers and query params.
from fastapi import Cookie
@app.get('/session')
async def session(session_id: str = Cookie(default=None)):
return {'session': session_id}Setting Headers on a Response
Inject a Response object to set headers while still returning normal data.
from fastapi import Response
@app.get('/items')
async def items(response: Response):
response.headers['X-Total-Count'] = '42'
return ['a', 'b']Setting Cookies
Call response.set_cookie to send a cookie back to the client. Add flags like httponly and secure for safety.
@app.post('/login')
async def login(response: Response):
response.set_cookie('session_id', 'abc123', httponly=True, secure=True)
return {'ok': True}Plain Text and HTML Responses
Return non-JSON content with specialized response classes.
from fastapi.responses import PlainTextResponse, HTMLResponse
@app.get('/text', response_class=PlainTextResponse)
async def text():
return 'hello'
@app.get('/page', response_class=HTMLResponse)
async def page():
return '<h1>Hi</h1>'Redirects
Send the client elsewhere with RedirectResponse. Choose the status code for permanent vs temporary redirects.
from fastapi.responses import RedirectResponse
@app.get('/old')
async def old():
return RedirectResponse(url='/new', status_code=301)Header Name Conversion
FastAPI converts underscores in parameter names to hyphens for headers. This pure example shows the same idea.
def to_header_name(param):
return '-'.join(w.capitalize() for w in param.split('_'))
print(to_header_name('user_agent'))
print(to_header_name('x_api_key'))Streaming Responses
For large or generated data, stream it with StreamingResponse so you do not buffer everything in memory.
from fastapi.responses import StreamingResponse
def rows():
for i in range(3):
yield f'row {i}\n'
@app.get('/export')
async def export():
return StreamingResponse(rows(), media_type='text/plain')Custom Status Codes
Set a default status for an operation with the status_code argument, or override per request via the injected Response.
from fastapi import status
@app.post('/items', status_code=status.HTTP_201_CREATED)
async def create():
return {'created': True}Security Notes
When setting auth cookies, prefer httponly=True (blocks JS access), secure=True (HTTPS only), and samesite to mitigate CSRF.
Quick Check
You declare x_api_key: str = Header(). Which incoming HTTP header does FastAPI map this to?
Recap
You handled the full request/response surface:
- Read headers and cookies with
HeaderandCookie. - Set headers and cookies via the injected
Response. - Returned plain text, HTML, redirects, and streaming responses.
- Applied secure cookie flags and custom status codes.
เรียนรู้ FastAPI Backend Development Bootcamp ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 21
- บทเรียน
- 84
คำถามที่พบบ่อย
บทเรียน “ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง”
อ่านส่วนหัวคำขอและคุกกี้ กำหนดค่าให้กับการตอบกลับ และส่งชนิดการตอบกลับแบบกำหนดเอง เช่น ข้อความธรรมดา HTML การเปลี่ยนเส้นทาง และการสตรีมใน FastAPI คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- โมเดล Pydantic สำหรับเนื้อหาคำขอ
- โมเดลการตอบกลับและรหัสสถานะ
- ข้อมูลแบบฟอร์มและการอัปโหลดไฟล์
- ส่วนหัว คุกกี้ และการตอบกลับแบบกำหนดเอง