POST operations

Introduction to FastAPI

Matt Eckerle

Software and Data Engineering Leader

GET vs. POST Operations

GET Operations

  • 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)

POST Operations

  • Traditional use: create a new object

  • Parameters sent via query string as well as request body

  • Requires an application or framework

    • e.g. cURL, requests
api = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
Introduction to FastAPI

HTTP Request Body

  • Data sent after the HTTP request header
  • Header specifies body encoding
  • Supports nested data structures
  • JSON and XML are the most common encodings for APIs
  • JSON is FastAPI default encoding

JSON Example

# Create a record for a movie review
{"movie": "The Neverending Story",
 "review": {"num_stars": 4,
            "text": "Great movie!",
            "public": true}}
Introduction to FastAPI

Using pydantic's BaseModel

pydantic: interface to define request and response body schemas

Note

We are nesting Review inside MovieReview

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
Introduction to FastAPI

Handling a POST Operation

POST endpoint to create a new movie review:

  • Endpoint: /reviews
  • Input: MovieReview (from previous slide)
  • Output: 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
1 https://fastapi.tiangolo.com/tutorial/sql-databases/#crud-utils
Introduction to FastAPI

Let's practice!

Introduction to FastAPI

Preparing Video For Download...