Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Developing FastAPI in VS Code

Developing FastAPI in VS Code

VS Code (full name Visual Studio Code) is a free, open-source, cross-platform code editor released by Microsoft.

VS Code supports Windows, macOS, and Linux, with powerful features and flexible extensibility.

VS Code tutorial:https://www.runoob.com/vscode/vscode-tutorial.html

Download address: https://code.visualstudio.com/ 。

The following extensions are recommended:

In addition, domestic companies Alibaba and ByteDance also have AI IDEs developed based on VS Code:

Alibaba Qoder
An AI programming IDE launched by Alibaba, deeply customized based on VS Code
Visit ->
ByteDance Trae
A new-generation AI-native development environment launched by ByteDance
Visit ->

Create a virtual environment

We can set up the Python development environment first; if it is already installed or configured, you can skip this step.

Install FastAPI and Uvicorn

pip install fastapi uvicorn


Create a FastAPI Application

In the fastapi-demo directory, create a main.py file with the following code:

Example

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.

get

(

"/"

)

async

def

read_root

(

)

:

   

return

{

"message"

:

"Hello, FastAPI!"

}

@

app.

get

(

"/items/{item_id}"

)

async

def

read_item

(

item_id:

int

,

q:

str

=

None

)

:

   

return

{

"item_id"

: item_id

,

"q"

: q

}

Run the application



uvicorn main:app --reload

Parameter Description:

Access the API


VS Code Development Tips

Select the menu in VS Code File > Open Folder…, open the fastapi-demo folder you just created.

When you open the project for the first time, VS Code will prompt "Do you trust this workspace?" - select "Yes, I trust the authors" to ensure extensions and resources run properly.

You can also use

code .

Open directly in the directory with the command,

.

the symbol indicates the current directory:



code .

Create requirements.txt

Create a new file (File > New Text File, or the shortcut ⌘N); you can also create it by clicking the new file icon to the right of the project name:

Add the following content (project dependencies):



fastapi

redis

types-redis

uvicorn

Save the file (⌘S) as requirements.txt.

Create a virtual environment

Create a virtual environment

Next, we can edit the main.py file:

Example

from

fastapi

import

FastAPI

app

=

FastAPI

(

)

@

app.

get

(

"/"

)

def

root

(

)

:

   

return

{

"message"

:

"Hello World"

}

Press F5 to start the debugger and run the code.

In the drop-down menu that appears, select the FastAPI debug configuration option from the list:

This automatically creates a debug configuration that uses uvicorn to start the application server through the debugger, allowing you to step through the source code to inspect its behavior.

You should see output similar to the following in the terminal:

In the terminal, Ctrl+click the displayed URL http://127.0.0.1:8000/ to open it in your browser:

If the default port is already in use:


Project Structure Recommendations

For large projects, the following structure is recommended:

my_fastapi_project/

├── app/

│   ├── __init__.py

│   ├── main.py         # 应用入口

│   ├── api/            # API路由

│   │   ├── __init__.py

│   │   ├── items.py

│   │   └── users.py

│   ├── models/         # 数据模型

│   │   ├── __init__.py

│   │   └── user.py

│   ├── schemas/        # Pydantic模型

│   │   ├── __init__.py

│   │   └── user.py

│   └── db/             # 数据库相关

│       ├── __init__.py

│       └── session.py

├── tests/              # 测试代码

│   ├── __init__.py

│   └── test_api.py

├── requirements.txt    # 依赖列表

└── .env                # 环境变量


Debugging and testing

Debugging FastAPI

In VS Code:

  1. Set breakpoints
  2. Press F5 to start debugging
  3. Access the API endpoints in the browser

Unit testing

Use pytest:

Example

test_main.py

from

fastapi.

testclient

import

TestClient

from

main

import

app

client

=

TestClient

(

app

)

def

test_read_root

(

)

:

    response

=

client.

get

(

"/"

)

   

assert

response.

status_code

==

200

   

assert

response.

json

(

)

==

{

"message"

:

"Hello, FastAPI!"

}

Run the tests:



pytest


Deployment Preparation

Production Server

Recommended:

Docker deployment

creation Dockerfile:

FROM python:3.9



WORKDIR /app



COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt



COPY . .



CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

Build and run:



docker build -t fastapi-app .

docker run -d -p 80:80 fastapi-app