Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Custom Response Classes - File, HTML, Redirect, Streaming, etc.

There are several custom response classes you can use to create an instance and return them directly from yourpath operations.

Read more about it in theFastAPI docs for Custom Response - HTML, Stream, File, others.

You can import them directly fromfastapi.responses:

fromfastapi.responsesimport(FileResponse,HTMLResponse,JSONResponse,ORJSONResponse,PlainTextResponse,RedirectResponse,Response,StreamingResponse,UJSONResponse,)

FastAPI Responses

There are a couple of custom FastAPI response classes, you can use them to optimize JSON performance.

fastapi.responses.UJSONResponse

UJSONResponse(content,status_code=200,headers=None,media_type=None,background=None,)

Bases:JSONResponse

JSON response using the high-performance ujson library to serialize data to JSON.

Read more about it in theFastAPI docs for Custom Response - HTML, Stream, File, others.

Source code instarlette/responses.py
181182183184185186187188189
def__init__(self,content:Any,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:super().__init__(content,status_code,headers,media_type,background)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type='application/json'

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code infastapi/responses.py
313233
defrender(self,content:Any)->bytes:assertujsonisnotNone,"ujson must be installed to use UJSONResponse"returnujson.dumps(content,ensure_ascii=False).encode("utf-8")

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.ORJSONResponse

ORJSONResponse(content,status_code=200,headers=None,media_type=None,background=None,)

Bases:JSONResponse

JSON response using the high-performance orjson library to serialize data to JSON.

Read more about it in theFastAPI docs for Custom Response - HTML, Stream, File, others.

Source code instarlette/responses.py
181182183184185186187188189
def__init__(self,content:Any,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:super().__init__(content,status_code,headers,media_type,background)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type='application/json'

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code infastapi/responses.py
4445464748
defrender(self,content:Any)->bytes:assertorjsonisnotNone,"orjson must be installed to use ORJSONResponse"returnorjson.dumps(content,option=orjson.OPT_NON_STR_KEYS|orjson.OPT_SERIALIZE_NUMPY)

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

Starlette Responses

You can read more about all of them in theFastAPI docs for Custom Response and in theStarlette docs about Responses.

fastapi.responses.FileResponse

FileResponse(path,status_code=200,headers=None,media_type=None,background=None,filename=None,stat_result=None,method=None,content_disposition_type="attachment",)

Bases:Response

Source code instarlette/responses.py
296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
def__init__(self,path:str|os.PathLike[str],status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,filename:str|None=None,stat_result:os.stat_result|None=None,method:str|None=None,content_disposition_type:str="attachment",)->None:self.path=pathself.status_code=status_codeself.filename=filenameifmethodisnotNone:warnings.warn("The 'method' parameter is not used, and it will be removed.",DeprecationWarning,)ifmedia_typeisNone:media_type=guess_type(filenameorpath)[0]or"text/plain"self.media_type=media_typeself.background=backgroundself.init_headers(headers)self.headers.setdefault("accept-ranges","bytes")ifself.filenameisnotNone:content_disposition_filename=quote(self.filename)ifcontent_disposition_filename!=self.filename:content_disposition=f"{content_disposition_type}; filename*=utf-8''{content_disposition_filename}"else:content_disposition=f'{content_disposition_type}; filename="{self.filename}"'self.headers.setdefault("content-disposition",content_disposition)self.stat_result=stat_resultifstat_resultisnotNone:self.set_stat_headers(stat_result)

chunk_sizeclass-attributeinstance-attribute

chunk_size=64*1024

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeinstance-attribute

media_type=media_type

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.HTMLResponse

HTMLResponse(content=None,status_code=200,headers=None,media_type=None,background=None,)

Bases:Response

Source code instarlette/responses.py
3435363738394041424344454647
def__init__(self,content:Any=None,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:self.status_code=status_codeifmedia_typeisnotNone:self.media_type=media_typeself.background=backgroundself.body=self.render(content)self.init_headers(headers)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type='text/html'

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.JSONResponse

JSONResponse(content,status_code=200,headers=None,media_type=None,background=None,)

Bases:Response

Source code instarlette/responses.py
181182183184185186187188189
def__init__(self,content:Any,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:super().__init__(content,status_code,headers,media_type,background)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type='application/json'

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
191192193194195196197198
defrender(self,content:Any)->bytes:returnjson.dumps(content,ensure_ascii=False,allow_nan=False,indent=None,separators=(",",":"),).encode("utf-8")

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.PlainTextResponse

PlainTextResponse(content=None,status_code=200,headers=None,media_type=None,background=None,)

Bases:Response

Source code instarlette/responses.py
3435363738394041424344454647
def__init__(self,content:Any=None,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:self.status_code=status_codeifmedia_typeisnotNone:self.media_type=media_typeself.background=backgroundself.body=self.render(content)self.init_headers(headers)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type='text/plain'

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.RedirectResponse

RedirectResponse(url,status_code=307,headers=None,background=None)

Bases:Response

Source code instarlette/responses.py
202203204205206207208209210
def__init__(self,url:str|URL,status_code:int=307,headers:Mapping[str,str]|None=None,background:BackgroundTask|None=None,)->None:super().__init__(content=b"",status_code=status_code,headers=headers,background=background)self.headers["location"]=quote(str(url),safe=":/%#?=@[]!$&'()*+,;")

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type=None

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.Response

Response(content=None,status_code=200,headers=None,media_type=None,background=None,)
Source code instarlette/responses.py
3435363738394041424344454647
def__init__(self,content:Any=None,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:self.status_code=status_codeifmedia_typeisnotNone:self.media_type=media_typeself.background=backgroundself.body=self.render(content)self.init_headers(headers)

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeclass-attributeinstance-attribute

media_type=None

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

fastapi.responses.StreamingResponse

StreamingResponse(content,status_code=200,headers=None,media_type=None,background=None,)

Bases:Response

Source code instarlette/responses.py
222223224225226227228229230231232233234235236237
def__init__(self,content:ContentStream,status_code:int=200,headers:Mapping[str,str]|None=None,media_type:str|None=None,background:BackgroundTask|None=None,)->None:ifisinstance(content,AsyncIterable):self.body_iterator=contentelse:self.body_iterator=iterate_in_threadpool(content)self.status_code=status_codeself.media_type=self.media_typeifmedia_typeisNoneelsemedia_typeself.background=backgroundself.init_headers(headers)

body_iteratorinstance-attribute

body_iterator

charsetclass-attributeinstance-attribute

charset='utf-8'

status_codeinstance-attribute

status_code=status_code

media_typeinstance-attribute

media_type=(media_typeifmedia_typeisNoneelsemedia_type)

bodyinstance-attribute

body=render(content)

backgroundinstance-attribute

background=background

headersproperty

headers

render

render(content)
Source code instarlette/responses.py
495051525354
defrender(self,content:Any)->bytes|memoryview:ifcontentisNone:returnb""ifisinstance(content,bytes|memoryview):returncontentreturncontent.encode(self.charset)# type: ignore

init_headers

init_headers(headers=None)
Source code instarlette/responses.py
565758596061626364656667686970717273747576777879808182
definit_headers(self,headers:Mapping[str,str]|None=None)->None:ifheadersisNone:raw_headers:list[tuple[bytes,bytes]]=[]populate_content_length=Truepopulate_content_type=Trueelse:raw_headers=[(k.lower().encode("latin-1"),v.encode("latin-1"))fork,vinheaders.items()]keys=[h[0]forhinraw_headers]populate_content_length=b"content-length"notinkeyspopulate_content_type=b"content-type"notinkeysbody=getattr(self,"body",None)if(bodyisnotNoneandpopulate_content_lengthandnot(self.status_code<200orself.status_codein(204,304))):content_length=str(len(body))raw_headers.append((b"content-length",content_length.encode("latin-1")))content_type=self.media_typeifcontent_typeisnotNoneandpopulate_content_type:ifcontent_type.startswith("text/")and"charset="notincontent_type.lower():content_type+="; charset="+self.charsetraw_headers.append((b"content-type",content_type.encode("latin-1")))self.raw_headers=raw_headers

set_cookie

set_cookie(key,value="",max_age=None,expires=None,path="/",domain=None,secure=False,httponly=False,samesite="lax",partitioned=False,)
Source code instarlette/responses.py
 90 91 92 93 94 95 96 97 98 99100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
defset_cookie(self,key:str,value:str="",max_age:int|None=None,expires:datetime|str|int|None=None,path:str|None="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",partitioned:bool=False,)->None:cookie:http.cookies.BaseCookie[str]=http.cookies.SimpleCookie()cookie[key]=valueifmax_ageisnotNone:cookie[key]["max-age"]=max_ageifexpiresisnotNone:ifisinstance(expires,datetime):cookie[key]["expires"]=format_datetime(expires,usegmt=True)else:cookie[key]["expires"]=expiresifpathisnotNone:cookie[key]["path"]=pathifdomainisnotNone:cookie[key]["domain"]=domainifsecure:cookie[key]["secure"]=Trueifhttponly:cookie[key]["httponly"]=TrueifsamesiteisnotNone:assertsamesite.lower()in["strict","lax","none",],"samesite must be either 'strict', 'lax' or 'none'"cookie[key]["samesite"]=samesiteifpartitioned:ifsys.version_info<(3,14):raiseValueError("Partitioned cookies are only supported in Python 3.14 and above.")# pragma: no covercookie[key]["partitioned"]=True# pragma: no covercookie_val=cookie.output(header="").strip()self.raw_headers.append((b"set-cookie",cookie_val.encode("latin-1")))

delete_cookie

delete_cookie(key,path="/",domain=None,secure=False,httponly=False,samesite="lax",)
Source code instarlette/responses.py
135136137138139140141142143144145146147148149150151152153
defdelete_cookie(self,key:str,path:str="/",domain:str|None=None,secure:bool=False,httponly:bool=False,samesite:Literal["lax","strict","none"]|None="lax",)->None:self.set_cookie(key,max_age=0,expires=0,path=path,domain=domain,secure=secure,httponly=httponly,samesite=samesite,)

[8]ページ先頭

©2009-2026 Movatter.jp