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)
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
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}
Start your API with Uvicorn:
uvicorn main:app --reload
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.