DEV Community

Gamey001
Gamey001

Posted on

Building a Dynamic Profile API with FastAPI

🎯 Task Overview

In Stage 0 of hng13 backend, the goal was simple but powerful:

Build a RESTful API endpoint /me that returns your profile details along with a random cat fact fetched dynamically from an external API.

*This task tested our understanding of:
*

API design with proper JSON structure

Integrating external APIs

Handling network errors gracefully

Returning dynamic UTC timestamps

Deploying a small but complete backend app

🧩 Stack & Tools

Language: Python

Framework: FastAPI 🏎️

HTTP Client: Requests

Environment Management: python-dotenv

Deployment: Railway

Testing: cURL & browser

βš™οΈ Project Setup
πŸ—‚οΈ Structure

backend-wizards-stage0/
β”‚
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ config.py
β”‚   └── utils/
β”‚       └── cat_facts.py
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ .env
β”œβ”€β”€ Procfile
└── README.md

Enter fullscreen mode Exit fullscreen mode

🧱 Main Endpoint

The /me endpoint returns:

{
  "status": "success",
  "user": {
    "email": "youremail@example.com",
    "name": "Your Full Name",
    "stack": "Python/FastAPI"
  },
  "timestamp": "2025-10-19T11:52:23.789Z",
  "fact": "Cats sleep for around 13 to 14 hours a day."
}
Enter fullscreen mode Exit fullscreen mode

⚑ Core Logic (simplified)

@app.get("/me")
async def get_profile():
    timestamp = datetime.now(timezone.utc).isoformat()
    response = {
        "status": "success",
        "user": {
            "email": Config.USER_EMAIL,
            "name": Config.USER_NAME,
            "stack": Config.USER_STACK
        },
        "timestamp": timestamp,
        "fact": fetch_cat_fact()
    }
    return JSONResponse(content=response)

Enter fullscreen mode Exit fullscreen mode

*Each request dynamically:
*

Fetches a new cat fact from Cat Facts API

Generates a fresh UTC timestamp

Returns all data in a consistent JSON schema

🧠 What I Learned
1️⃣ Working with External APIs

Using the requests library, I learned to:

Handle timeouts and connection errors

Extract specific JSON keys safely

Return fallback messages when the API fails

Example:

def fetch_cat_fact():
    try:
        res = requests.get("https://catfact.ninja/fact", timeout=5)
        res.raise_for_status()
        return res.json().get("fact")
    except requests.RequestException:
        return "Could not fetch cat fact at the moment."

Enter fullscreen mode Exit fullscreen mode

*Error Handling Matters
*

Instead of letting the entire app crash when the Cat Facts API fails, the function gracefully returns a friendly message.
This makes the API robust and user-friendly β€” a key real-world backend skill.

3️⃣ Dynamic Data and Time Formatting

I learned how to generate ISO 8601 UTC timestamps:

datetime.now(timezone.utc).isoformat()
Enter fullscreen mode Exit fullscreen mode

Every new request shows a fresh timestamp ⏰ β€” confirming the endpoint is truly dynamic.

4️⃣ Deployment & Environment Variables

This task reinforced best practices:

Keeping sensitive data (like name/email) in a .env file

Configuring environment variables in the hosting platform (Railway)

Using a Procfile to define the startup command

My Procfile:

web: uvicorn app.main:app --host 0.0.0.0 --port ${PORT:-8000}

Enter fullscreen mode Exit fullscreen mode

Deployment on Railway was smooth:

Push code to GitHub

Connect repo on Railway

Add environment variables (USER_EMAIL, USER_NAME, USER_STACK)

Deploy πŸš€

Visit https://yourappurl.up.railway.app/me

πŸ“Έ Screenshots

(Add screenshots here of your running API on localhost and on Railway)

βœ… Local run on http://127.0.0.1:8000/me

☁️ Live endpoint showing real-time cat facts

{
  "status": "success",
  "user": {
    "email": "jdoe@example.com",
    "name": "John Doe",
    "stack": "Python/FastAPI"
  },
  "timestamp": "2025-10-19T13:09:45.123Z",
  "fact": "Cats use their whiskers to detect objects and navigate tight spaces."
}

Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Takeaways

A small API can teach big backend fundamentals β€” request handling, responses, error management, and clean JSON formatting.

Using FastAPI makes development extremely fast and intuitive with automatic docs at /docs.

I learned to appreciate clean error handling, environment separation, and deployment best practices.

🏁 Final Thoughts

This task reminded me that clarity + consistency = good backend design.
Even a simple endpoint like /me can demonstrate:

Professional structure

Error resilience

Proper documentation

You can check out the GitHub repository here:
πŸ‘‰ GitHub Repo

And the live API here:
πŸ‘‰ Live Endpoint

Author: Gamaliel Dashua

Stack: Python / FastAPI
Challenge: Hng13 - Backend Stage 0 πŸš€

Top comments (0)