FastAPI Quickstart Part 02: Creating a Dummy User API with Pydantic and Implementing GET/PUT Calls | #python #fastapi #letscode

Posted by

FastAPI Quickstart part:02 – Dummy User API with Pydantic, GET/PUT calls

In part 02 of our FastAPI Quickstart series, we will create a Dummy User API using Pydantic for data validation and perform GET and PUT calls to retrieve and update user information. FastAPI is a modern web framework for building APIs with Python that is fast, easy to use, and highly performant.

Setting up the Project

First, make sure you have FastAPI and Pydantic installed in your Python environment. You can install them using pip:


pip install fastapi
pip install pydantic

Create a new Python file, for example, dummy_user_api.py, and import the necessary modules:


from fastapi import FastAPI
from pydantic import BaseModel

Defining the Data Model

We will create a Pydantic model to represent the user data. Add the following code to your Python file:


class User(BaseModel):
id: int
name: str
email: str

Creating the FastAPI App

Next, initialize a new instance of the FastAPI app and define two routes for handling GET and PUT requests:


app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "name": "John Doe", "email": "john.doe@example.com"}

@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
return {"user_id": user_id, "name": user.name, "email": user.email}

Running the App

To run the FastAPI app, use the uvicorn server. In your terminal, navigate to the directory containing your Python file and run the following command:


uvicorn dummy_user_api:app --reload

You can now access the Dummy User API at http://localhost:8000/users/{user_id}, where {user_id} is the ID of the user you want to retrieve or update. Use tools like Postman or curl to send GET and PUT requests to the API and test its functionality.

That’s it for part 02 of our FastAPI Quickstart series. Stay tuned for more tutorials on building APIs with FastAPI and Python. Happy coding!

#python #fastapi #letscode