Guides › FastAPI Hello World: Build Your Own Tiny API
FastAPI Hello World: Build Your Own Tiny API
The practice API on this site is built with FastAPI. You can build the smallest possible version yourself in a minute.
Install
pip install fastapi uvicorn
Write main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hello, world"}
Run it
uvicorn main:app --reload
Open http://127.0.0.1:8000/hello in your browser. FastAPI also builds a page at /docs where you can try every endpoint with a button.
Your turn
Add a second route, like /names/{id}, that returns one name from a list. Compare it with the live practice API.
Challenge
Add GET /names/{id} to your app. It should return one name, and a 404 with a helpful message when the id does not exist.
Show the answer
Look the id up in a list, and raise HTTPException with status 404 when nothing matches. Then open /docs on your own app and press the button.
from fastapi import FastAPI, HTTPException
app = FastAPI()
NAMES = [{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}]
@app.get("/names/{name_id}")
def one_name(name_id: int):
for n in NAMES:
if n["id"] == name_id:
return n
raise HTTPException(status_code=404, detail="No name with that id.")