HTTP Methods In FastAPI


In the previous article on FastAPI Getting Started With FastAPI, we have understood what FastAPI is, what advantages FastAPI brings when developing APIs using FastAPI, and also developed a simple REST API with GET endpoints, this article is going to showcase PUT and POST operations and also describes object Modeling using Pydantic. Let’s explore.


We will begin with creating a Simple POST operation that does nothing, it returns an empty response, doing that is very similar as it’s in GET'/employees')
def createEmployee():
return {}

The data from the client to the API is sent as Request Body, in FastAPI for declaring Request Body the Pydantic Models should be used. The Pydantic module has BaseModel class all the models are simply created using BaseModel class.

from pydantic import BaseModel
class Employee(BaseModel):
id: int
name: str
dept: str

That’s it, our Employee model is ready, there is a lot more to it, which we will cover in future articles. Let’s modify the endpoint'/employees')
def createEmployee(employee: Employee):
return employee

In the createEmployee method, we are passing the Employee Request Body and returning the same, lets's check the docs.

Upon executing the endpoint

Further modifying the code, let’s add the Employee object in the Employee List.'/employees')
def createEmployee(employee: Employee):
id =
employee_details[id] = employee
return employee_details[id]

Let’s search the employee with id 5, which is recently created and the GET endpoint is covered in the earlier article.


Let’s update the employee’s department using the PUT operation, the implementation is straight-forward

def updateEmployee(empId:int, employee:Employee):
employee_details[empId] = employee
return employee_details[empId]

Get the Employee by id 5 to validate whether the PUT is a success or not.


In the article, we have covered PUT/POST and Pydantic Base Models, slowly we are reaching there. In the upcoming articles, Pydantic in detail will be covered and also will explore classes for better documentation.

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles