Speedy FastAPI API for Creating, Reading, Updating, and Deleting Data.

Posted by

Quick FastAPI CRUD API

Introducing Quick FastAPI CRUD API

FastAPI is a modern web framework for building APIs with Python. It is fast, easy to use, and has great performance. In this article, we will discuss how to create a CRUD (Create, Read, Update, Delete) API using FastAPI.

Setting up FastAPI

First, you need to install FastAPI using pip:

pip install fastapi

Then, you can create a new Python file and import FastAPI:

from fastapi import FastAPI
app = FastAPI()

Creating a CRUD API

Now, let’s create a simple CRUD API with FastAPI. Below is an example of how to define routes for creating, reading, updating, and deleting data:

from fastapi import FastAPI

app = FastAPI()

# Sample data
items = []

# Create
@app.post("/items/")
async def create_item(item: str):
    items.append(item)
    return {"message": "Item added successfully"}

# Read
@app.get("/items/")
async def read_items():
    return {"items": items}

# Update
@app.put("/items/{item_id}")
async def update_item(item_id: int, new_item: str):
    items[item_id] = new_item
    return {"message": "Item updated successfully"}

# Delete
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    del items[item_id]
    return {"message": "Item deleted successfully"}

Testing the API

You can test the API by running it in your local environment and using tools like cURL or Postman to send requests to the defined endpoints. Here are some examples:

curl -X POST -d 'item=apple' http://localhost:8000/items/
curl -X GET http://localhost:8000/items/
curl -X PUT -d 'new_item=banana' http://localhost:8000/items/0
curl -X DELETE http://localhost:8000/items/0

Conclusion

FastAPI makes it easy to create powerful CRUD APIs with Python. Its intuitive syntax and automatic validation make it a great choice for building web APIs. Try it out for your next project!

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

Thanks for the video 🙂