@app.get
- Python course
- Advanced
- Lesson 50/83
- 5 min
Learn to define routes with @app.get("/path").
@app.get
The @app.get("/path") decorator binds a GET route to a function. When a request hits that path, FastAPI calls the function and turns its return value into a response.
@app.get("/merhaba")
def merhaba():
return {"msg": "selam"}The path string is the path part of the URL (e.g. /merhaba). If the return value is a dict, FastAPI responds with structured data.
Return value
When a route function returns a dict, FastAPI turns it into a structured-data response. Lists, numbers and strings are converted similarly.
@app.get("/sayi")
def sayi():
return {"deger": 42}
# response body: {"deger":42}If the function returns a BaseModel instance, FastAPI also turns it into structured data. This lets you shape API responses easily.
Practice Define and test a GET route
Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With @app.get("/merhaba") define def merhaba(): returning {"msg": "selam"}. Create a client with client = TestClient(app). Print the response body with print(client.get("/merhaba").text).
Starter code
# bring in FastAPI from fastapi
# bring in TestClient
# define app
# add a get function at '/merhaba' (returning msg 'selam')
# create a client with TestClient and print the response bodySample solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/merhaba")
def merhaba():
return {"msg": "selam"}
client = TestClient(app)
print(client.get("/merhaba").text)Expected output
{"msg":"selam"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the get decorator
@____("/merhaba")
def merhaba():
return {"msg": "selam"}
@app.get("/merhaba")
def merhaba():
return {"msg": "selam"}
Explanation: @app.get('/path') defines a GET route.
2 What does the @app.get decorator do?
- Deletes a function
- Binds a function to a GET route Correct answer
- Hides a function
- Calls a function twice
Explanation: @app.get('/path') binds a function to a GET route.
3 Match the @app.get concepts
| Term | Meaning |
|---|---|
@app.get |
Defines a GET route |
/merhaba |
Is the path string |
def merhaba |
Is the function definition |
return {...} |
Is the response body |