Skip to main content

Command Palette

Search for a command to run...

🚀 Getting Started with FastAPI: Building Python APIs the Smart Way

Published
4 min readView as Markdown

✍️ “I’m new to web APIs, but I know some Python. I want to learn how to build something real — like a login system or a loan checker. Where do I start?”

You start here — with FastAPI.

FastAPI is one of the fastest and easiest ways to build web APIs in Python. It’s perfect for beginners, yet powerful enough for real-world applications.

Let’s walk through everything step by step: what FastAPI is, how it works, and how to build a real example using input, validation, and clean responses using Pydantic and JSON.


🧠 What is FastAPI?

FastAPI is a modern Python framework for building web APIs.

Think of it like this:

  • 🔁 You write functions in Python

  • 🌐 FastAPI turns those into URLs (routes) that the web can access

  • 🧠 It automatically handles input, checks for errors, and sends back responses


📦 Install FastAPI and Uvicorn

Before you start, open your terminal and install the tools:

bashCopyEditpip install fastapi uvicorn
  • fastapi gives you the framework

  • uvicorn is the server that runs your app (think of it as the "door" between your code and the internet)


🔥 Your First FastAPI App

Create a file called main.py and add:

pythonCopyEditfrom fastapi import FastAPI

app = FastAPI()

@app.get("/hello")
def say_hello():
    return {"message": "Hello, FastAPI is running!"}

Then run it:

bashCopyEdituvicorn main:app --reload

Visit:

arduinoCopyEdithttp://127.0.0.1:8000/hello

You’ll see:

jsonCopyEdit{"message": "Hello, FastAPI is running!"}

🎉 You just made your first API!


🛠️ Understanding Routes: @app.get() vs @app.post()

FastAPI uses decorators like:

  • @app.get("/something") – For getting data

  • @app.post("/something") – For submitting data (like a form)

  • @app.put("/something") – For updating

  • @app.delete("/something") – For deleting

Example:

pythonCopyEdit@app.get("/status")
def check_status():
    return {"status": "Online"}

📤 Sending Data with POST — Example: Loan Checker

Now let’s make a real example where a user sends loan details to see if they’re eligible.

Step 1: Import Pydantic

pythonCopyEditfrom pydantic import BaseModel

Pydantic lets you define what kind of data you expect, and FastAPI will validate it for you.


Step 2: Define Input Data Model

pythonCopyEditclass LoanInput(BaseModel):
    name: str
    age: int
    income: int
    score: int

This means:

  • name: must be a string

  • age, income, score: must be integers


Step 3: Create the API Route

pythonCopyEdit@app.post("/check-loan")
def check_loan(data: LoanInput):
    if data.age < 21:
        return {"message": f"Age {data.age} is too young to be eligible."}
    if data.income < 3000:
        return {"message": f"Income {data.income} is too low."}
    if data.score < 500:
        return {"message": f"Score {data.score} is too low."}

    return {"message": f"Dear {data.name}, you are eligible for the loan!"}

✅ FastAPI will automatically:

  • Accept JSON input

  • Validate types

  • Return a JSON response


📄 How to Send the Input

Visit this awesome URL:

arduinoCopyEdithttp://127.0.0.1:8000/docs

It opens the Swagger UI — a built-in tool where you can test your API without writing any frontend!

Click POST /check-loan, then click Try it out, and enter:

jsonCopyEdit{
  "name": "Lorenzo",
  "age": 25,
  "income": 4000,
  "score": 750
}

📩 You’ll get:

jsonCopyEdit{
  "message": "Dear Lorenzo, you are eligible for the loan!"
}

🧠 Wait… What is JSON again?

JSON = JavaScript Object Notation. It’s a way of structuring data like this:

jsonCopyEdit{
  "name": "Lorenzo",
  "age": 25
}

In FastAPI, you send and receive data as JSON, and Pydantic helps validate and read it in Python.


🔐 Bonus: Simple Login Example

Want to build a login route?

pythonCopyEditclass LoginInput(BaseModel):
    username: str
    password: str

@app.post("/login")
def login(user: LoginInput):
    if user.username == "admin" and user.password == "1234":
        return {"message": "Login successful!"}
    return {"message": "Invalid credentials."}

Test this in /docs by sending:

jsonCopyEdit{
  "username": "admin",
  "password": "1234"
}

📚 Summary — What You’ve Learned

ConceptWhat It Means
FastAPI()Creates the app
@app.get()Route to return data (no input)
@app.post()Route to accept input data
PydanticUsed to define and validate input
JSONData format sent to/from the browser
Swagger UIBuilt-in tool to test your API
UvicornServer that runs your FastAPI app

More from this blog

Data Science

39 posts