Complete the code to import FastAPI and create an app instance.
from fastapi import [1] app = [1]()
You need to import FastAPI and create an instance of it to start your app.
Complete the code to define a GET endpoint that returns a welcome message.
@app.[1]("/") async def read_root(): return {"message": "Hello, FastAPI!"}
The @app.get decorator defines a GET HTTP method endpoint.
Fix the error in the code to receive JSON data in a POST request.
from fastapi import FastAPI, [1] app = FastAPI() @app.post("/items") async def create_item(item = [1]()): return item
Use Body to declare that the parameter should come from the request body as JSON.
Fill both blanks to define a POST endpoint that receives a message and returns it with a status.
from fastapi import FastAPI, [1] from pydantic import BaseModel app = FastAPI() class Message(BaseModel): text: str @app.post("/send") async def send_message(message: [2] = [1]()): return {"status": "received", "message": message.text}
Use Body to receive the message from the request body and Message as the data model.
Fill all three blanks to create a WebSocket endpoint that sends back received messages.
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/[1]") async def websocket_endpoint(websocket: [2]): await websocket.accept() data = await websocket.[3]() await websocket.send_text(f"Message received: {data}")
The WebSocket endpoint path is usually something like '/ws'. The parameter type is WebSocket. To receive text data, use receive_text().