一、新建文件Helloworld_FastAPI.py
1 2 3 4 5 6 7 8 9 10 11 12 13 | # -*- coding: UTF-8 -*- from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/") async def main(): return {"message": "Hello,FastAPI"} if __name__ == '__main__': uvicorn.run(app, host="127.0.0.1", port=8000) |
右键run code就可以看到

image.png
二、Uvicorn 配置热更新
1 2 3 4 5 6 7 | # -*- coding: UTF-8 -*- if __name__ == '__main__': import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000) |
Uvicorn是一款闪电般的“ ASGI”服务器。
它在单个过程中运行异步Python Web代码。
他的run函数有个config配置文件,可以根据需要修改,我这里的 host="127.0.0.1",
port=8000,是默认配置,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | class Config: def __init__( self, app, host="127.0.0.1", port=8000, uds=None, fd=None, loop="auto", http="auto", ws="auto", lifespan="auto", env_file=None, log_config=LOGGING_CONFIG, log_level=None, access_log=True, use_colors=None, interface="auto", debug=False, reload=False, reload_dirs=None, workers=None, proxy_headers=True, forwarded_allow_ips=None, root_path="", limit_concurrency=None, limit_max_requests=None, backlog=2048, timeout_keep_alive=5, timeout_notify=30, callback_notify=None, ssl_keyfile=None, ssl_certfile=None, ssl_version=SSL_PROTOCOL_VERSION, ssl_cert_reqs=ssl.CERT_NONE, ssl_ca_certs=None, ssl_ciphers="TLSv1", headers=None, ): |
可以改成
1 | uvicorn.run(app='helloworld:app', host="127.0.0.1", port=8000, reload=True, debug=True) |
这样之后就可以启动热更新重启服务了!
1 2 3 | helloworld: helloworld.py文件( app:app = FastAPI() 在helloworld.py内创建的对象。 reload:在代码更改后重新启动服务器。 只有在开发时才使用这个参数。 |

image.png
启动服务会看到
1 2 3 4 | INFO: Started reloader process [17961] INFO: Started server process [17962] INFO: Waiting for application startup. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) |
三、路由方法有 GET, POST, PUT, PATCH, DELETE 和 OPTIONS。
1 2 3 4 5 6 7 8 9 10 | @app.post("/") @app.put("/") @app.delete("/") @app.get("/") @app.options("/") @app.head("/") @app.patch("/") @app.trace("/") async def root(): return {"message": "HelloWorld"} |
具体后面文章会说
四、交互的API文档
现在进入 http://127.0.0.1:8000/docs.
你将会看见自动的交互式API文档,该文档由Swagger UI提供

image.png
点击get方法的try it out execute会测试该接口

image.png
五、备用API文档
现在,转到http://127.0.0.1:8000/redoc
您将看到备用自动文档(由ReDoc提供)。

image.png
六、下载API接口文档
如果你需要提供你的API接口,那么只需要一行命令,即可下载api文件,一般保存为api.json
1 | curl -o api.json http://127.0.0.1:8000/openapi.json |