Sending data in with POST requests

All of this time, we used the @app.get method, which represents the expected HTTP GET request. As its name implies, this command is supposed to retrieve information and therefore is designed to store small snippets of data in itself. This data could be passed as resource—part of the URL, like complaint_type in the preceding exampleor appended as a parameter, like hour in our first example.

However, there are cases when you need to pass a significant data structure as part of your request. For that, there is another command: POST. You see, every request, technically, has three means of passing information:

  • URL, which can contain resources and parameters
  • BODY, which can store arbitrary data
  • HEADERS, a small section for metadata, which describes desired server behavior, and should not be used for API behavior

On top of that, the HTTP specification recommends not to use a body part for GET requests, as it goes against the semantics. The bottom line is this: if you need to pass a rich data structure to an API, use the POST method and keep this data structure in its body.

Let's imagine that, for some reason, our application now needs to handle the input of new complaints. Every complaint stores multiple pieces of information: location, time, type of complaint, some description, and so on. And of course, there are some rules on what values are acceptable for each data type.

To deal with data structures and validation, FastAPI uses another package: pydantic. Let's describe the structure we're expecting as a pydantic object. As we'll have to specify the complaint type, we'll reuse the Enum object from the preceding example:

from pydantic import BaseModel
from datetime import datetime

class Complaint(BaseModel):
complaint_type:ComplaintType
timestamp:datetime = datetime.now()
lat:float
lon:float
description:str

@app.post("/input/")
def enter_complaint(body: Complaint):
return body.dict() # for the sake of simplicity just returns value back

Here, we declare a Complaint object, which includes the complaint type as Enum, and four other parameters. As we wrap our function with a post methoda variable not defined in the path is assumed to be the body. We define this parameter to be Complaint object, by definition.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.53.216