Starting a FastAPI Application with Uvicorn

FastAPI has quickly become one of the most popular web frameworks for Python due to its simplicity and high performance. Running it under Gunicorn, WSGI server is common practice but here we'll start our app directly using `uvicorn`, which provides better async capabilities out-of-the-box with FastAPI. Below are the steps required to launch a basic Uvicorn application:

Before you begin, ensure that Python 3.6+ is installed on your system and pip package installer has been set up correctly (pip >=20.1). If not yet created an API project directory named `my_fastapi`, run the following commands to initialize one: ```bash mkdir my_fastapi && cd my_fastapi/ python3 -m venv venv source ./venv/bin/activate (Linux or macOS) pip install --upgrade pip wheel # Use this if you encounter `BrokenLinkError` after installing FastAPI and Uvicorn using their get-started commands. This ensures dependencies are properly installed in the virtual environment instead of global Python path. pip install fastapi[all] uvicorn grequests psutil (Windows) OR pip install -U "uvicorn[standard]>=0.13.4,<0.15" asyncio --user # This ensures that only the necessary packages are installed within your virtual environment without any additional ones included in `fastapi[all]`. ``` After installation is successful: deactivate with this command to leave Python's venv and proceed further into application setup steps below. You can reactivate it using `./venv/bin/activate` if required for future operations like debugging or testing your app locally without installing dependencies globally (though not needed during development).

Now that you have created a virtual environment and installed FastAPI, Uvicorn along with necessary packages (`grequests`), `psutil`, etc., follow the below-mentioned steps to launch an API application. Create or update `__init__.py` file inside your project directory as follows - ```python # __init__.py content: start_app() function definitions here... # from fastapi import FastAPI from .routes import * # assuming routes are defined in a separate module named 'routes' with all necessary handler functions. app = FastAPI() export default app ``` The `start_app()` function should define your main startup logic which starts the Uvicorn server instance that listens for incoming HTTP requests and invokes corresponding route handlers accordingly:

Create a file named `__init__.py` inside `my_fastapi/`, where FastAPI app object (`app`) is created using the following code snippet as shown below with respective imports, and startup logic encapsulated within it: ```python # __init__.py content for start-up function definition here... # from fastapi import FastAPI from .routes import * # assuming routes are defined in a separate module named 'routes' which contains all necessary handler functions. Ensure that your route modules reside inside `my_fastapi/` as well if not already there (or any preferred location). These files should be created following the same structure: # my_fastapi/routes/__init__.py content here... # [empty or with code snippet to define all handler functions] ``` Within `__init__.py`, create a `start_app()` function which initializes and starts your Uvicorn server instance like this -

Now you need to start the FastAPI application on localhost port **8000** as follows- execute below command in terminal within project directory (`my_fastapi/` for this tutorial) - ```bash uvicorn my_fastapi:app --port 8000 --host 127.0.0.1 & # using `&` to run the server as a background job (use `nohup uvicorn my_fastapi:app --port $PORT --bind-hostname localhost &` if you wish it not terminate after closing terminal) ``` This command starts an instance of your FastAPI app on port **8000**. If successful, this will display a message with details about the running server and its URL (http://127.0.0.1:8000/). You can now access it through browser or tools like cURL command in terminal to test various endpoints defined on your `/routes` file where all handler functions reside under `my_fastapi/` directory structure, as shown below - ```bash curl --location 'http://127.0.0.1:8000/health' # Healthcheck endpoint that returns status code "OK" or something similar upon successful execution depending on what logic implemented inside it & function definition within corresponding handler file in routes folder of your project directory (my_fastapi/). If unavailable locally due to firewall restrictions, add `--host 192.0.3546783` parameter while starting Uvicorn server instance from terminal with command as shown previously - ``` For testing endpoints that handle async operations and return `StreamingResponse`, use these commands instead: ```bash curl --location 'http://localhost:8000/stream_example?payload=sample' # replace '/stream_example' by your customized stream endpoint pathname & include optional query params like so `& payload=` (e.g., `{"message":"Hello, World!"}`), which can be accessed via browser or cURL command above - ``` ## Troubleshooting Common Issues: 🕵️‍♂️ Uvicorn server instance might terminate unexpectedly for a few reasons; here are some potential fixes based on common scenarios where this issue arises (along with respective commands to run): - Application code or dependencies have unhandled exceptions leading FastAPI app termination: To identify & fix these, use uvicorn builtin 'Trace' functionality by running below command - ```bash uvicorn my_fastapi --trace # Run server instance in trace mode which outputs detailed stack traces upon encountering an error instead of terminating immediately. This helps locate where exactly the issue lies within codebase (usually inside corresponding handler function definitions). If found out, fix them accordingly and try re-running uvicorn - ``` If required but not yet set up logging in your application using builtin `logging` module or any third party libraries like python's powerful `loguru`, then run this command while starting server instance (to log & debug errors)- : ```bash uvicorn my_fastapi --port $PORT -v 3 # Use '-v 3' for additional info logging from FastAPI application startup, execution flow etc. including exceptions if found unhandled somewhere along with their stack traces which can aid debugging significantly (if not yet implemented) & run server instance as usual by using command below- ``` If above steps do not resolve issues then try running Uvicorn in `foreground` instead of background job, like so: ```bash uvicorn my_fastapi:app --port $PORT # Without '&' at end (to block terminal) - Run server instance here & use following command- ``` This will help to identify if there are any interfering processes running on the same port as well. Once confirmed, stop them beforehand using appropriate commands/methods specific for your OS such as `kill` or other tools provided by it (e.g., Windows Task Manager), then restart server instance again & see results- ```bash uvicorn my_fastapi:app --port $PORT # Repeat steps till you successfully run FastAPI app on desired port - ``` If still facing issues while starting Uvicorn Server Instance, refer these additional resources (linked at bottom of this tutorial) for more advanced troubleshooting tips & tricks specific to your OS or scenario: - [Uvicorn FAQs](https://www.uvicorns.org/faq/#troubleshooting ) - For common Uvicorn related queries (including start and stop server instance commands) with various solutions provided for issues like app termination, slow performance etc., as well as some best practices to optimize uvicorn instances in terms of resource utilization & improved speed. - [FastAPI troubleshoot tips](https://fastapi.tiangolo.com/faq/#troubleshooting ) - FAQs section for FastAPI framework specifically addressing issues related start or run server instance, request handling etc., along with their respective solutions provided in detail (easiest to understand & implement). - [Uvicorn documentation](https://www.uvicorns.org/en/documentation/) - Main Uvicorn Framework official docs providing step by step guide on how start FastAPI app instances using uvicorn server runner, setup logging configurations etc., along with other related information like performance optimization techniques & troubleshooting tips- ```
Quality, Reliability & Service
Thank You For Visiting
Brooks Computing Systems - Jacksonville
Visit https://bcs.archman.us