Skip to content

I implemented a simple Backend using the FastAPI in Python. FastAPI is a modern, fast ( high - performance ) web framework for building API's with python based on standard Python type hints.

Notifications You must be signed in to change notification settings

sanketsingh01/FastAPI-Backend

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation

FastAPI

FastAPI Setup

Dependencies

  • Python 3.9+

Setup

  • mkdir backend
  • cd backend
  • Create a virtual environment: python3 -m venv venv
  • Activate the virtual environment:
    • Mac/Linux: source ./venv/bin/activate
    • Windows: .\venv\Scripts\activate
  • Install the dependencies from requirements.txt
    • pip install -r requirements.txt

Basic FastAPI Without Auth

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List

class Fruit(BaseModel):
    name: str

class Fruits(BaseModel):
    fruits: List[Fruit]

app = FastAPI(debug=True)

origins = [
    "http://localhost:3000",
    # Add more origins here
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

memory_db = {"fruits": []}

@app.get("/fruits", response_model=Fruits)
def get_fruits():
    return Fruits(fruits=memory_db["fruits"])

@app.post("/fruits")
def add_fruit(fruit: Fruit):
    memory_db["fruits"].append(fruit)
    return fruit


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Run the API

  • First Way: python main.py
  • Second Way(Recommended): uvicorn main:app --reload

About

I implemented a simple Backend using the FastAPI in Python. FastAPI is a modern, fast ( high - performance ) web framework for building API's with python based on standard Python type hints.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages