Performing Basic CRUD Operations without a Database using FastAPI

Posted by

Basic CRUD without database using FastAPI

Basic CRUD without database using FastAPI

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. In this article, we will learn how to create a basic CRUD (Create, Read, Update, Delete) application without using a database using FastAPI.

Prerequisites

Before we start, make sure you have Python 3.7+ installed on your system. You can install FastAPI and Uvicorn (ASGI server) using pip:


pip install fastapi
pip install uvicorn

Creating a basic CRUD application

First, we need to create a FastAPI application with the following code:


from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

@app.put("/items/{item_id}")
def update_item(item_id: int):
    return {"item_id": item_id, "updated": "yes"}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    return {"item_id": item_id, "deleted": "yes"}

Save the above code in a file named main.py. Now, to run the application, use the following command:


uvicorn main:app --reload

Now go to http://127.0.0.1:8000/ in your web browser, and you should see the “Hello World” message. You can also try the other endpoints for basic CRUD operations:

  • http://127.0.0.1:8000/items/1
  • http://127.0.0.1:8000/items/1?q=test
  • http://127.0.0.1:8000/items/1 (PUT request)
  • http://127.0.0.1:8000/items/1 (DELETE request)

Conclusion

With just a few lines of code, we have created a basic CRUD application without using a database using FastAPI. FastAPI makes it easy to build high-performance APIs with Python and is a great choice for building web applications.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Vasile4e4ek
10 months ago

Nightcall Kavinsky