SoFunction
Updated on 2024-11-18

Python implementation of the Web server FastAPI steps in detail

1. Introduction

FastAPI is a modern, fast (and high-performance) web framework for building APIs, using Python 3.6+ and based on standard Python type hints.

Documentation:
Source Code:/tiangolo/fastapi

Key Features.

  • Fast: Very high performance on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python web frameworks.
  • Efficient coding: Increase the speed of functional development by approximately 200% to 300%. *
  • Fewer bugs: Reduce human (developer) caused errors by about 40%. *●
  • Smart: Excellent editor support. Auto-completion everywhere, reducing debugging time.
  • Simple: designed to be easy to use and learn, with less time spent reading documentation.
  • Short: minimizes code duplication. Rich functionality through different parameter declarations. fewer bugs.
  • Robust: produce usable levels of code. And automatically generated interactive documentation.
  • Standardization: Based on (and fully compatible with) the relevant open standards for APIs: OpenAPI (formerly known as Swagger) and JSON Schema.

2. Installation

pip install fastapi
or
pip install fastapi[all]

The command to run the server is as follows:

uvicorn main:app --reload

3. Official examples

Using FastAPI requires Python version greater than or equal to 3.6.

3.1 Getting Started Example The Python test code is as follows ():

# -*- coding:utf-8 -*-
from fastapi import FastAPI
app = FastAPI()
@("/")
async def root():
    return {"message": "Hello World"}

The results of the run are as follows:
The command to run the server is as follows:

uvicorn main:app --reload

3.2 Cross-domain CORS

CORS or "Cross Domain Resource Sharing" refers to the situation where a front-end running in a browser has JavaScript code that communicates with a back-end, but the back-end is in a different "source" than the front-end.

A source is a combination of protocol (http, https), domain (, localhost,) and port (80, 443, 8080). Therefore, these are all different sources:

http://localhost
https://localhost
http://localhost:8080

The Python test code is as follows (test_fastapi.py):

# -*- coding:utf-8 -*-
from typing import Union
from fastapi import FastAPI, Request
import uvicorn
from  import CORSMiddleware
app = FastAPI()
# Make apps cross-domain capable
# origins = ["*"]
origins = [
    "",
    "",
    "http://localhost",
    "http://localhost:8080",
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# @("/") 
# async def root(): 
#     return {"Hello": "World"}
@("/")
def read_root():
    return {"message": "Hello World, book-loving Mu."}
@("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}
@("/api/sum") 
def get_sum(req: Request): 
    a, b = req.query_params['a'], req.query_params['b'] 
    return int(a) + int(b) 
@("/api/sum2") 
async def get_sum(req: Request): 
    content = await () 
    a, b = content['a'], content['b'] 
    return a + b
@("/api/sum3")
def get_sum2(a: int, b: int): 
    return int(a) + int(b)
if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The results of the run are as follows:

FastAPI automatically provides an interactive documentation similar to Swagger, which we can access by typing "localhost:8000/docs".

3.3 File operations

The return json data can be: JSONResponse, UJSONResponse, ORJSONResponse, Content-Type is application/json; return html is HTMLResponse, Content-Type is text/html; return PlainTextResponse, Content-Type is text/plain.
There are also three responses, which return redirects, byte streams, and files.

(1) The Python test redirection code is as follows:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from  import RedirectResponse
import uvicorn
app = FastAPI()
@("/index")
async def index():
    return RedirectResponse("")
@("/")
def main():
    return {"message": "Hello World, book-loving Mu."}
if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The results of the run are as follows:

(2) The Python test byte stream code is as follows:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from  import StreamingResponse
import uvicorn
app = FastAPI()
async def test_bytearray():
    for i in range(5):
        yield f"byteArray: {i} bytes ".encode("utf-8")
@("/index")
async def index():
    return StreamingResponse(test_bytearray())
@("/")
def main():
    return {"message": "Hello World, book-loving Mu."}
if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The results of the run are as follows:

(3) The Python test text file code is as follows:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from  import StreamingResponse
import uvicorn
app = FastAPI()
@("/index")
async def index():
    return StreamingResponse(open("test_tornado.py", encoding="utf-8"))
@("/")
def main():
    return {"message": "Hello World, book-loving Mu."}
if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The results of the run are as follows:

(4) The Python test binary code is as follows:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from  import FileResponse, StreamingResponse
import uvicorn
app = FastAPI()
@("/download_file")
async def index():
    return FileResponse("test_fastapi.py", filename="")
@("/get_file/")
async def download_files():
    return FileResponse("test_fastapi.py")
@("/get_image/")
async def download_files_stream():
    f = open("static\\images\\", mode="rb")
    return StreamingResponse(f, media_type="image/jpg")
@("/")
def main():
    return {"message": "Hello World, book-loving Mu."}
if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The results of the run are as follows:

3.4 WebSocket Python test code is as follows:

# -*- coding:utf-8 -*-
from fastapi import FastAPI, Request
from  import WebSocket
import uvicorn
app = FastAPI()
@("/myws")
async def ws(websocket: WebSocket):
    await ()
    while True:
        # data = await websocket.receive_bytes()
        # data = await websocket.receive_json()
        data = await websocket.receive_text()
        print("received: ", data)
        await websocket.send_text(f"received: {data}")
@("/")
def main():
    return {"message": "Hello World, book-loving Mu."}

if __name__ == "__main__":
    ("test_fastapi:app", host="127.0.0.1", port=8000
                , log_level="info", reload=True, debug=True)

The HTML client test code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tornado Websocket Test</title>
</head>
<body>
<body onload='onLoad();'>
Message to send: <input type="text" />
<input type="button" onclick="sendMsg();" value="Send."/>
</body>
</body>
<script type="text/javascript">
    var ws;

    function onLoad() {
        ws = new WebSocket("ws://127.0.0.1:8000/myws");
		 = function() {
           ('connect ok.')
		   ("Hello, world");
		};
		 = function (evt) {
		   ()
		};
         = function () { 
            ("onclose") 
        }
    }
    function sendMsg() {
        (('msg').value);
    }
</script>
</html>

The results of the run are as follows:

to this article on the implementation of Python Web server (FastAPI article is introduced to this, more related Python Web server content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future!