FastAPI Hello World application - Python Web development introductory tutorial | Daoman PythonAI
#FastAPI Hello World App
📂 Stage: Stage 1 - Rapid Foundation Building (Basics) 🔗 Prerequisite knowledge: fastapi-intro-advantages · environment-setup
Table of contents
Hello World: 5 lines to get the first interface
Let's get started and create a minimalist but complete FastAPI application. Create a new one in the project root directorymain.pydocument:
Dismantle key logic line by line
- Import FastAPI classes: Just like using Python's standard library, from
fastapiGet the core tools in the module. - Create application instance:
appIt is the "brain" of the entire API, and all routing, configuration, and middleware will be mounted on it. - The role of decorator:
@app.get("/")Accomplishes two things at the same time - tells FastAPI: "When a GET request is received and the path is the root path/**, call the followinghello_worldfunction". - Automatic JSON serialization: Return an ordinary Python dictionary (or object with Pydantic model), FastAPI will automatically convert it into a standard JSON format response, no need to call it manually
json.dumps。
If you have used Flask or Django before, you will find that FastAPI is simpler to write, and type hints and automatic documentation are its most eye-catching features.
Run the application and explore the automatic documentation
FastAPI officially recommends using ASGI server Uvicorn to run applications, which supports production-level features such as hot reloading and multi-processing.
Preparation: Activate virtual environment
If you have created a virtual environment in the environment-setup chapter, you need to activate it first:
- Windows(PowerShell / CMD):
- macOS / Linux:
Start command (development mode)
Parameter description:
main:app: Specifymain.pyin the fileappExample--reload: Essential for development, automatically restart the server after code changes--host 0.0.0.0: Allow other devices in the LAN to access (only local debugging can be omitted)--port 8000: Listen to port 8000 (the default is also 8000, which can be omitted)
After successful startup, a log similar to the following will appear on the terminal:
📖 Free interactive API documentation
One of the most surprising features of FastAPI - automatically generated, directly interactive API documentation. After starting the service, just access the following two addresses directly:
- Swagger UI (debugging tool): http://127.0.0.1:8000/docs The interface is intuitive and supports sending requests online, viewing responses, and even downloading calling code snippets in multiple languages (Python, JavaScript, Java, etc.).
- ReDoc (suitable for external display): http://127.0.0.1:8000/redoc The layout is more concise and elegant, and it is suitable as a product-level API document for teams or partners to read.
Every time you add or modify an interface, you only need to refresh the document page, and all changes will be immediately visible, which greatly improves development efficiency.
Rapidly expand core interactive functions
Hello World is just an appetizer. Next, we will quickly add three of the most commonly used interaction modes in web development to feel the simplicity and power of FastAPI.
1. Path parameters (such as obtaining a single product)
Path parameters are variables embedded in the URL path, using{}Package, FastAPI will automatically complete type conversion and basic verification:
Test it in Swagger UI:
- input
item_id = 123:Return normally,123is an integer - input
item_id = abc: Swagger directly prompts an error, and the server returns a 422 verification failure message, which is very clear.
2. Query parameters (such as paging and search)
Query parameters are at the end of the URL?The following key-value pairs, such as/items?skip=0&limit=10. FastAPI supports optional parameters and default values:
3. POST request body (such as creating a product)
In a POST request, the client sends data (usually JSON) to the server through the request body. FastAPI is paired with the Pydantic model to accurately define the data structure and perform strict verification - this is one of the core reasons why it can achieve high performance and low bug rate.
First define a Pydantic model to clarify the types and constraints of product fields:
Click "Try it out" in the Swagger UI and paste the following JSON to see the return result with the total price:
Pitfall avoidance guide and development gadgets
✅ Pitfall 1: The order of routing definitions
FastAPI performs route matching in the order defined in the code, so the fixed path needs to be placed before the variable path, otherwise matching errors may occur.
✅ Avoid Pitfalls 2: The Difference between Development Mode and Production Mode
- Development Mode: Can be used
--reload, can also be passed in when creating the applicationdebug=True, but these** must not appear in the production environment**. - Production Mode: removed
--reloadanddebug=True, subsequent advanced tutorials will introduce multi-process deployment and other solutions.
🛠️ Development gadget: print request information
When debugging, you can add a simple middleware to record the method, path and response time of each request:
Put this code at the front of the application, each request will output clear logs, and the processing time will be added to the response headerX-Process-Time, which is convenient for front-end or API debugging tools to view directly.
Summary
Through this introductory tutorial that can be started in just a few minutes, you have mastered the core three-piece set of the FastAPI Hello World application:
- Create Application: Pass
FastAPI()Get application examples - Define route: use
@app.get/post/...()Decorator, binding HTTP methods, paths and handlers - Parameters and verification: Flexibly use path parameters, query parameters and Pydantic request bodies to enjoy automatic type conversion and verification
In addition, don’t forget to make good use of Swagger UI to debug the interface in real time. It can help you save a lot of time in writing test requests.
In the next article, we will learn more about Advanced verification of path parameters and query parameters, so stay tuned ~

