Python API Tutorial for Beginners | Build Your First REST API Step by Step

Python API Tutorial for Beginners | Build Your First REST API Step by Step

In this beginner-friendly tutorial, you’ll learn how to build a simple REST API using FastAPI and test it using Postman.

We’ll create, read, update, and delete (CRUD) items in memory.

Prerequisites

Before you begin, make sure you have:

  • Python 3.10 or newer is installed

  • Basic knowledge of JSON and HTTP requests

  • Postman installed for API testing

Step 1 — Create Project Folder and Virtual Environment

Open your Terminal and run:

# Create project folder and go inside mkdir fastapi_api cd fastapi_api # Create virtual environment named 'venv' python3 -m venv venv # Activate the virtual environment source venv/bin/activate

After activation, your terminal prompt will show (venv) indicating you’re inside the virtual environment.

Step 2 — Install FastAPI and Uvicorn

With the virtual environment activated, run:

python3 -m pip install fastapi==0.120.0 uvicorn==0.38.0
  • FastAPI is the framework to build the API.

  • Uvicorn is the ASGI server that runs your app.

Step 3 — Create main.py with API Code

Create a file named main.py inside fastapi_api folder and paste this code:

from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import Optional app = FastAPI(title="Simple Items API") # Data model class Item(BaseModel): id: Optional[int] = None name: str description: Optional[str] = "" # In-memory storage items = {} next_id = 1 # Get all items @app.get("/items") def list_items(): return list(items.values()) # Get single item by ID @app.get("/items/{item_id}") def get_item(item_id: int): item = items.get(item_id) if not item: raise HTTPException(status_code=404, detail="Item not found") return item # Create new item @app.post("/items", status_code=201) def create_item(item: Item): global next_id item.id = next_id items[next_id] = item.dict() next_id += 1 return items[item.id] # Update existing item @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") updated = items[item_id] updated["name"] = item.name or updated["name"] updated["description"] = item.description or updated.get("description", "") items[item_id] = updated return updated # Delete item @app.delete("/items/{item_id}", status_code=204) def delete_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") del items[item_id] return None

Step 4 — Run FastAPI Server

Run the server with this command (inside the project folder and with your virtual environment activated):

python3 -m uvicorn main:app --reload --port 8000

Step 5 — Access Interactive API Documentation

Open these URLs in your browser:

You can test all endpoints interactively here without Postman.

Step 6 — Test API Endpoints with Postman

Use Postman to test these endpoints:

🟢 Create Item (POST)

  • URL: POST http://127.0.0.1:8000/items

  • Headers: Content-Type: application/json

  • Body (raw JSON):

{ "name": "Apple", "description": "Fresh red apple" }
  • Response:

{ "id": 1, "name": "Apple", "description": "Fresh red apple" }

🔵 Get Item (GET)

  • URL: GET http://127.0.0.1:8000/items/1

  • Response:

{ "id": 1, "name": "Apple", "description": "Fresh red apple" }

🟠 Update Item (PUT)

  • URL: PUT http://127.0.0.1:8000/items/1

  • Headers: Content-Type: application/json

  • Body (raw JSON):

{ "name": "Green Apple" }
  • Response:

{ "id": 1, "name": "Green Apple", "description": "Fresh red apple" }

🔴 Delete Item (DELETE)

  • URL: DELETE http://127.0.0.1:8000/items/1

  • Response:
    Status code 204 No Content (no body)

⚪ Get All Items (GET)

  • URL: GET http://127.0.0.1:8000/items

  • Response Example:

[ { "id": 1, "name": "Green Apple", "description": "Fresh red apple" } ]

Step 7 — Summary

FrameworkFeaturesDocumentation
FlaskLightweight, beginner-friendlyflask.palletsprojects.com
FastAPIHigh-performance, async-ready, built-in docs, validationfastapi.tiangolo.com
Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close