POST-operationer

Introduktion till FastAPI

Matt Eckerle

Software and Data Engineering Leader

GET vs. POST-operationer

GET-operationer

  • Traditionell användning: hämta information om ett objekt

  • Parametrar skickas via frågesträng

  • Kan skickas från en webbläsare

api = "http://moviereviews.co/reviews/1"
response = requests.get(api)

POST-operationer

  • Traditionell användning: skapa ett nytt objekt

  • Parametrar skickas via frågesträng och i requestkroppen

  • Kräver ett program eller ramverk

    • t.ex. cURL, requests
api = "http://moviereviews.co/reviews/"
body = {"text": "A great movie!"}
response = requests.post(api, json=body)
Introduktion till FastAPI

HTTP-requestkropp

  • Data skickas efter HTTP-requestens huvud
  • Huvudet anger kroppens kodning
  • Stöder nästlade datastrukturer
  • JSON och XML är vanligast för API:er
  • JSON är FastAPI:s standardkodning

JSON-exempel

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

Använda pydantics BaseModel

pydantic: gränssnitt för att definiera scheman för request- och responsekroppar

Obs

Vi nästlar Review inuti 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
Introduktion till FastAPI

Hantera en POST-operation

POST-endpoint för att skapa en ny filmrecension:

  • Endpoint: /reviews
  • Indata: MovieReview (från föregående bild)
  • Utdata: db_review (definieras på annan plats)
@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
Introduktion till FastAPI

Dags att öva!

Introduktion till FastAPI

Preparing Video For Download...