Building a Simple REST API with FastAPI...

Building a Simple REST API with FastAPI...

What is an API?

An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. It consist of Endpoints : URL path, Request, Response, Authentication ( optional ).

Then, what is a REST API?

REST API (Representational State Transfer Application Programming Interface) is a type of web API. It has HTTP methods like GET ( Read all items ), POST ( Create an item ), PUT ( Update an item ), DELETE ( Delete an item ).

There are many ways to build REST APIs, but here we will use a Python framework called FastAPI.

Why choose FASTAPI?

Because it's fast, easy to use, modern and comes with built-in documentation.

Let's dive in...

First, we need to install FastAPI on our machine. Run the following command:

pip install fastapi uvicorn        

Next, we will define the Item class. It will have name (string), age (int), and education (string) as its parameters. Since we are building a simple API, we won’t store data in a database but in a simple array/list (in-memory).

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    age: int
    education: str = None        

Let's build crud operations...

# POST request
@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    items_db.append(item)
    return item        

The complete code looks like the below. Save it as main.py.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Item(BaseModel):
    name: str
    age: int
    education: str = None

items_db = []

@app.post("/items/", response_model=Item)
async def create_item(item: Item):
    items_db.append(item)
    return item

@app.get("/items/", response_model=List[Item])
async def get_items():
    return items_db

@app.get("/items/{item_id}", response_model=Item)
async def get_item(item_id: int):
    if item_id < 0 or item_id >= len(items_db):
        raise HTTPException(status_code=404, detail="Item not found")
    return items_db[item_id]

@app.put("/items/{item_id}", response_model=Item)
async def update_item(item_id: int, item: Item):
    if item_id < 0 or item_id >= len(items_db):
        raise HTTPException(status_code=404, detail="Item not found")
    items_db[item_id] = item
    return item

@app.delete("/items/{item_id}", response_model=Item)
async def delete_item(item_id: int):
    if item_id < 0 or item_id >= len(items_db):
        raise HTTPException(status_code=404, detail="Item not found")
    deleted_item = items_db.pop(item_id)
    return deleted_item
        

Now, run this project using below command.

uvicorn main:app --reload        

This will start a development server at https://127.0.0.1:8000. Append the CRUD URLs to use the API. Also, https://127.0.0.1:8000/docs generates documentation and a Swagger UI, where you can see example requests and try out the API.


Further you can extend this API by adding more complex logic based on your project requirements. Whether it's integrating a database, adding authentication and authorization, implementing advanced error handling, or optimizing performance with caching and rate-limiting.. the possibilities are endless!
Happy coding!        


Md Shakawat Hossain

Software Engineer | Native Android | Cross-Platform Solutions | API development

1 个月

Great start to an essential guide!

回复

要查看或添加评论,请登录

Smita Vatgal的更多文章

  • Git Isn’t Optional !

    Git Isn’t Optional !

    In Episode 4 we understood the need for dockerization and building basic docker file. Here is the link : https://www.

  • Dockerizing a REST API with JWT Authentication...

    Dockerizing a REST API with JWT Authentication...

    In Episode 3, we understood the need for JWT authentication and how to implement it in a REST API. link Everything…

    1 条评论
  • Data Visualization: Simplifying Complexity at a Glance

    Data Visualization: Simplifying Complexity at a Glance

    A chart can tell a story that rows of numbers can’t. That’s the power of data visualization! For example below is the…

    1 条评论
  • Authentication using JWT (JSON Web Token)

    Authentication using JWT (JSON Web Token)

    In Episode 2, we learned how to integrate a database to store the requests sent to the API. Now, let’s explore how to…

  • Integrating SQLite with FastAPI

    Integrating SQLite with FastAPI

    In our previous article, we walked through a step-by-step guide to building a simple REST API using FastAPI. Here’s the…

社区洞察

其他会员也浏览了