Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

4.2. GET 请求

4.2.1. 返回图片

			
from fastapi import FastAPI, File, Response

app = FastAPI()


@app.get("/image")
async def show_image():
    with open("image.jpg", "rb") as image_file:
        image_data = image_file.read()
    return Response(content=image_data, media_type="image/jpeg")			
			
			
			
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path

app = FastAPI()

@app.get("/image")
async def get_image():
    image_path = Path("path/to/your/image.jpg")
    if not image_path.is_file():
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path)			
			
			

4.2.2. 路径参数

		
from fastapi import FastAPI

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id):
    return {"item_id": item_id}