make me an api using fastapi
- User
user: make me an api using fastapi
- Assistant
user: make me an api using fastapi
Sure! Below is a simple example of how to create a RESTful API using FastAPI. This example will expose a few endpoints for managing a list of items.
You can install FastAPI and Uvicorn with pip. Run this command in your terminal:
pip install fastapi uvicorn
Create a new Python file, for example main.py, and add the following code:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List
app = FastAPI()
# Define a Pydantic model for the items
class Item(BaseModel):
id: int
name: str
description: str = None
# In-memory storage for items
items = []
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items.append(item)
return item
@app.get("/items/", response_model=List[Item])
def read_items():
return items
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
for item in items:
if item.id == item_id:
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item: Item):
for index, existing_item in enumerate(items):
if existing_item.id == item_id:
items[index] = item
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
for index, item in enumerate(items):
if item.id == item_id:
del items[index]
return {"detail": "Item deleted"}
raise HTTPException(status_code=404, detail="Item not found")
To run the FastAPI application, use the command:
uvicorn main:app --reload
This will start the server, and you’ll see output indicating that the application is running. By default, it will be accessible at http://127.0.0.1:8000.
You can test the API using tools like curl, Postman, or directly in the browser. FastAPI automatically generates an interactive API documentation that you can access at http://127.0.0.1:8000/docs.
Create an item (POST to /items/):
{
"id": 1,
"name": "Item 1",
"description": "This is item 1"
}
Get all items (GET to /items/).
Get an item by ID (GET to /items/1).
Update an item (PUT to /items/1):
{
"id": 1,
"name": "Updated Item",
"description": "This is the updated item 1"
}
Delete an item (DELETE to /items/1).
That’s it! You now have a simple API up and running using FastAPI. You can expand upon this by adding more features, validation, and error handling as needed!
Not yet included in a published release.