FastAPI Hello World应用程序
一个简单的Hello World API,由FastAPI和MCP SSE支持构建。
特性
- 返回Hello World消息的根端点
- 采用名称参数的动态问候端点
- OpenAI与GPT-4o集成,实现高级AI聊天功能
- 带有Swagger UI的API自动文档
先决条件
- Python 3.7+(用于本地设置)
- pip(Python包安装程序)
- OpenAI API密钥(用于
/openai端点) - Docker(可选,用于容器化设置)
安装说明
您可以在本地或使用Docker运行此应用程序。
本地设置
1.克隆存储库
git clone https://github.com/xxradar/mcp-test-repo.git
cd mcp-test-repo2.创建虚拟环境(可选但推荐)
# On macOS/Linux
python -m venv venv
source venv/bin/activate
# On Windows
python -m venv venv
venv\Scripts\activate3.安装依赖项
pip install -r requirements.txt4.运行应用程序
uvicorn main:app --reload应用程序将在以下时间启动并可用http://127.0.0.1:8000
或者,您可以直接使用Python运行应用程序:
python main.pyDocker设置
1.克隆存储库
git clone https://github.com/xxradar/mcp-test-repo.git
cd mcp-test-repo2.构建Docker镜像
docker build -t fastapi-hello-world .3.运行Docker容器
docker run -p 8000:8000 fastapi-hello-world该应用程序将在http://localhost:8000
API终点
GET /:返回一条简单的Hello World消息GET /hello/{name}:返回具有提供名称的个性化问候语GET /openai:返回OpenAI GPT-4o模型的响应(接受可选prompt查询参数)GET /docs:Swagger用户界面文档GET /redoc:重新记录文档
OpenAI集成
这 /openai 端点使用OpenAI的GPT-4o模型,并要求将OpenAI API密钥设置为环境变量:
本地设置
# Set the OpenAI API key as an environment variable
export OPENAI_API_KEY=your_api_key_here
# Run the application
uvicorn main:app --reloadDocker设置
# Run the Docker container with the OpenAI API key
docker run -p 8000:8000 -e OPENAI_API_KEY=your_api_key_here fastapi-hello-world示例用法
使用curl
# Get Hello World message
curl http://127.0.0.1:8000/
# Get personalized greeting
curl http://127.0.0.1:8000/hello/John
# Get OpenAI chat completion with default prompt
curl http://127.0.0.1:8000/openai
# Get OpenAI chat completion with custom prompt
curl "http://127.0.0.1:8000/openai?prompt=Tell%20me%20a%20joke%20about%20programming"使用MCP
连接到MCP检查器
npx @modelcontextprotocol/inspector使用网络浏览器
- 打开http://127.0.0.1:8000/在浏览器中查找Hello World消息
- 打开http://127.0.0.1:8000/hello/John在浏览器中输入个性化问候语
- 打开http://127.0.0.1:8000/openai在浏览器中,使用默认提示从OpenAI获取响应
- 打开http://127.0.0.1:8000/openai?prompt=What%20is%20FastAPI?在浏览器中获取有关FastAPI的响应
- 打开http://127.0.0.1:8000/docsSwagger UI文档
发展
要更改应用程序,请编辑 main.py 文件。如果您使用以下命令运行服务器,它将自动重新加载 --reload 旗帜。
