DEV Community

Free Python Code
Free Python Code

Posted on

Create API using FastAPI and Python

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
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

step 2

Import modules

from fastapi import FastAPI
from pydantic import BaseModel
from uuid import uuid4
import json
Enter fullscreen mode Exit fullscreen mode

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}


Enter fullscreen mode Exit fullscreen mode

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())
Enter fullscreen mode Exit fullscreen mode

result

{'msg': 'done', 'task': {'id': 'fcfa65f4-30a8-489a-a39f-8445fa7bd881', 'name': 'test 123', 'description': '123', 'done': 0}}
Enter fullscreen mode Exit fullscreen mode

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

Top comments (0)