FastAPI helps you quickly create web apps that can handle requests and send responses. It makes building APIs simple and fast.
0
0
First FastAPI application
Introduction
You want to create a simple web service that returns data.
You need a quick way to build an API for your app or project.
You want to learn how web servers work with Python.
You want to test ideas by making a small web app.
You want to build a backend that talks to a frontend app.
Syntax
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello World"}
FastAPI() creates the app instance.
@app.get("/") means this function runs when someone visits the home URL with a GET request.
Examples
This example responds to GET requests at /hello with a greeting message.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/hello") async def say_hello(): return {"greeting": "Hello FastAPI!"}
This example shows how to get a path parameter from the URL and return it.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}
Sample Program
This is the simplest FastAPI app. When you run it and visit the home page, it sends back a JSON message.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello World"}
OutputSuccess
Important Notes
Run this app with: uvicorn filename:app --reload replacing filename with your Python file name.
Use async def for your route functions to allow FastAPI to handle many requests efficiently.
FastAPI automatically converts your return values to JSON responses.
Summary
FastAPI lets you create web apps with just a few lines of code.
Use decorators like @app.get() to define routes.
Your functions return data that FastAPI sends as JSON to users.