Introduction to FastAPI
Matt Eckerle
Software and Data Engineering Leader
Traditional use: request info about an object
Parameters sent via query string
Can be sent from a web browser
api = "http://moviereviews.co/reviews/1"
response = requests.get(api)
Traditional use: create a new object
Parameters sent via query string as well as request body
Requires an application or framework
cURL
, requests
api = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
JSON Example
# Create a record for a movie review
{"movie": "The Neverending Story",
"review": {"num_stars": 4,
"text": "Great movie!",
"public": true}}
pydantic
: interface to define request and response body schemas
Note
We are nesting
Review
insideMovieReview
from pydantic import BaseModel
class Review(BaseModel):
num_stars: int
text: str
public: bool = False
class MovieReview(BaseModel):
movie: str
# Nest Review in MovieReview
review: Review
POST endpoint to create a new movie review:
/reviews
MovieReview
(from previous slide)db_review
(defined elsewhere)@app.post("/reviews", response_model=DbReview)
def create_review(review: MovieReview):
# Persist the movie review to the database
db_review = crud.create_review(review)
# Return the review including database ID
return db_review
Introduction to FastAPI