3.2. FastAPI Install
pip install fastapipip install uvicorn- minimal (pure Python) dependenciespip install uvicorn[standard]- "Cython-based" dependencies and other "extras"
3.2.1. Install
To install FastAPI execute:
$ python -m pip install fastapi
To install uvicorn there are two options: uvicorn
or uvicorn[standard].
uvicorn:
Install uvicorn with minimal (pure Python) dependencies
uvicorn[standard]:
Install uvicorn with "Cython-based" dependencies (where possible) and other "optional extras"
The event loop
uvloopwill be installed and used if possibleThe HTTP protocol will be handled by
httptoolsif possibleThe Websocket protocol will be handled by
websocketsif possibleIf you want to use
wsprotoyou'd need to install it manuallyThe
--reloaderflag in development mode will usewatchgodWindows users will have
coloramainstalled for the colored logs
python-dotenvwill be installed should you want to use the--env-fileoption
PyYAMLwill be installed to allow you to provide a.yamlfile to--log-config, if desired
# Install uvicorn with minimal (pure Python) dependencies
$ python -m pip install uvicorn
# Install uvicorn with "Cython-based" dependencies (where possible) and other "optional extras"
$ python -m pip install 'uvicorn[standard]'
3.2.2. App
Create file main.py with content:
>>> from fastapi import FastAPI
>>>
>>>
>>> app = FastAPI()
>>>
>>> @app.get('/')
... def index():
... return {'message': 'hello world'}
3.2.3. Run
uvicorn- lightning-fast ASGI server implementation, usinguvloopandhttptoolsmain- name of the module to run (filename without.pyextension)app- name of theFastAPIclass instance (inside of themain.pyfile)--reload- reload webserver each time whenmain.pychanges (flag is optional)
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [63402] using statreload
INFO: Started server process [63404]
INFO: Waiting for application startup.
INFO: Application startup complete.
Optional configuration arguments:
$ uvicorn main:app --workers 2
$ uvicorn main:app --reload --port 8000
$ uvicorn main:app --reload --host 0.0.0.0 --port 8000
Open browser at http://127.0.0.1:8000/
3.2.4. Run Configuration
3.2.5. Debug
PyCharm Run Configuration
Set breakpoint
Run Debugger
Step Over
Create file main.py:
>>> import uvicorn
>>> from fastapi import FastAPI
>>> app = FastAPI()
>>>
>>>
>>> @app.get('/')
... def index():
... return {'data': 'hello world'}
>>>
>>>
>>> if __name__ == '__main__':
... uvicorn.run('main:app', host='127.0.0.1', port=8000)
$ python main.py
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [68005] using watchgod
INFO: Started server process [68007]
INFO: Waiting for application startup.
INFO: Application startup complete.