FastApi Basic CRUD REST API

Posted by

In this tutorial, we will cover the basics of creating a RESTful API with CRUD operations using FastAPI in Python. FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

To get started, make sure you have Python installed on your machine. You can install FastAPI using pip:

pip install fastapi

Additionally, you will need an ASGI server to run FastAPI. We recommend using Uvicorn:

pip install uvicorn

Now that you have FastAPI and Uvicorn installed, let’s create our API. We will start by creating a new Python file, for example, main.py.

from fastapi import FastAPI

app = FastAPI()

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

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items/")
def create_item(item: dict):
    return item

@app.put("/items/{item_id}")
def update_item(item_id: int, item: dict):
    return {"item_id": item_id, "updated_item": item}

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

In this code snippet, we have defined a FastAPI app with five endpoints: a GET request to read the root, a GET request to read an item by its ID, a POST request to create an item, a PUT request to update an item by its ID, and a DELETE request to delete an item by its ID.

To run the FastAPI app, use Uvicorn to serve the application:

uvicorn main:app --reload

Now you can access your API at http://localhost:8000. You can test the API using tools like Postman or cURL.

Here are some example requests you can make to test your API:

  • GET request to read the root: http://localhost:8000/
  • GET request to read an item by its ID: http://localhost:8000/items/1
  • POST request to create an item: http://localhost:8000/items/ with a JSON body containing the item data
  • PUT request to update an item by its ID: http://localhost:8000/items/1 with a JSON body containing the updated item data
  • DELETE request to delete an item by its ID: http://localhost:8000/items/1

That’s it! You have successfully created a basic RESTful API with CRUD operations using FastAPI in Python. Feel free to enhance your API by adding more endpoints, validations, and error handling as needed.