Skip to content

Instantly share code, notes, and snippets.

@codingforentrepreneurs
Last active February 28, 2024 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingforentrepreneurs/5d965eecbd31c44e0551bbbeaa105f7c to your computer and use it in GitHub Desktop.
Save codingforentrepreneurs/5d965eecbd31c44e0551bbbeaa105f7c to your computer and use it in GitHub Desktop.
Your First Python Rest API App. Learn Python Web Development Basics

Your First Python Rest API App

Python and many ways to create a Rest API endpoint. This one uses FastAP which is designed to easily create API endpoints for nearly anything.

REST APIs are here so software can talk to other software. REST APIs typically send JSON data types (instead of HTML like websites do for humans)

Step 1: Setup

Create virtual environment, activate it, and install FastAPI and Uvicorn:

python3 -m venv venv
source venv/bin/activate

If Windows, use .\venv\Scripts\activate

python -m pip install pip fastapi uvicorn --upgrade

Step 2: Create Your API with Models

In main.py, define a Pydantic model for your data and create both GET and POST endpoints:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

# Define a Pydantic model for the data structure
class Item(BaseModel):
    name: str
    description: str = None
    price: float
    tax: float = None

# GET endpoint
@app.get("/")
def read_root():
    return {"Hello": "World"}

# POST endpoint to calculate an item cost
@app.post("/cart/")
def create_cart(item: Item):
    tax_total = item.price * item.tax
    total = item.price + tax_total
    return {'total': total}

Step 3: Run the API

Start your API with Uvicorn:

uvicorn main:app --reload

Step 4: Test Endpoints with CURL

To test the POST endpoint, use the following CURL command:

curl -X 'POST' 'http://127.0.0.1:8000/cart/' -H 'Content-Type: application/json'   -d '{
  "name": "Example Item",
  "description": "This is an example item.",
  "price": 9.99,
  "tax": 0.2
}'

The curl command makes it easy to send an HTTP request. In this case, we're sending an HTTP POST request which is very common for sending, or POSTing, data from one app to another app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment