Hi ๐๐
In this post, I will share with you how to create an API using FastAPI and Python. In this post, I will create a simple task app ๐ค
step 1
Create a JSON file to store tasks and add this task for testing.
{
"tasks": [
{
"id": "44gds64sgd6464dsg44456646",
"name": "test",
"descripption": "test",
"done" : 0
}
]
}
step 2
Import modules
from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4
import json
step 3
Create the API
from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4
import json
app = FastAPI()
class Task(BaseModel):
id : str
name : str
description : str
done : int
@app.get('/')
def home():
return {"msg": "welcome in my api"}
@app.get('/tasks')
def get_all_tasks():
return {"tasks" : json.load(open('database.json', 'r'))['tasks']}
@app.post('/add_task')
def add_task(task : Task):
tasks = json.load(open('database.json', 'r'))
tasks['tasks'].append({
"id" : str(uuid4()),
"name" : task.name,
"description" : task.description,
"done" : 0
})
json.dump(tasks, open('database.json', 'w'), indent = 4)
return {"msg": "done", "task": task}
Add new task using requests
import requests
from uuid import uuid4
task = {
"id" : str(uuid4()),
"name" : "test 123",
"description" : "123",
"done" : 0
}
res = requests.post('http://127.0.0.1:8000/add_task', json=task)
print(res.json())
result
{'msg': 'done', 'task': {'id': 'fcfa65f4-30a8-489a-a39f-8445fa7bd881', 'name': 'test 123', 'description': '123', 'done': 0}}
Now we're done ๐ค
Don't forget to like and follow ๐
Support me on PayPal ๐ค
https://www.paypal.com/paypalme/amr396
Top comments (0)