FastAPI app
- Python course
- Advanced
- Lesson 49/83
- 5 min
Learn to create an app with FastAPI().
FastAPI app
FastAPI() creates an application object. It registers routes and dispatches requests to the matching function. With TestClient you test the app without running a server.
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
def root():
return {"msg": "merhaba"}
client = TestClient(app)
print(client.get("/").text)TestClient queries the app like an HTTP server; the body comes from resp.text, the status from resp.status_code.
Using TestClient
The TestClient(app) call returns a client object. On it you make requests with methods like get and post. You read the response body with resp.text.
client = TestClient(app)
resp = client.get("/")
print(resp.status_code) # 200
print(resp.text) # bodyTestClient offers the same API as the requests library, so it feels familiar.
Practice Test a FastAPI app
Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With the @app.get("/") decorator define def root(): returning {"msg": "merhaba"}. Create a client with client = TestClient(app). Print the response body with print(client.get("/").text).
Starter code
# bring in FastAPI from fastapi
# bring in TestClient
# define app (using the FastAPI class)
# add a get function at the root path (returning msg 'merhaba')
# create a client with TestClient and print the response bodySample solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
def root():
return {"msg": "merhaba"}
client = TestClient(app)
print(client.get("/").text)Expected output
{"msg":"merhaba"}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which class tests a FastAPI app without a server?
- HTTPServer
- FastAPI
- BaseModel
- TestClient Correct answer
Explanation: TestClient queries the FastAPI app in memory.
2 Complete the TestClient call
from fastapi.testclient import TestClient
client = ____(app)
from fastapi.testclient import TestClient
client = TestClient(app)
Explanation: TestClient(app) creates a test client.
3 Match the FastAPI app concepts
| Term | Meaning |
|---|---|
FastAPI() |
Creates the app |
TestClient(app) |
Gives a client |
client.get(url) |
Makes a request |
resp.text |
Gives body |