How to Create a Simple Time API Using Python
Welcome to Cyber Supto! I'm Supto. In this tutorial, we will learn how to create a simple Time API using Python. This API will provide the current time, and you can expand it later to include features like different timezones, date formatting, and more.
We will use FastAPI, one of the fastest and easiest Python frameworks for building APIs.
Prerequisites
- Basic knowledge of Python
- Python installed (version 3.7+)
- Basic understanding of REST APIs
- pip installed for managing packages
Step 1: Install FastAPI and Uvicorn
FastAPI is used to build the API, and Uvicorn is the server that runs it.
pip install fastapi uvicorn
Step 2: Create Your Project Structure
time_api/
│
├── main.py
We will write all the code in main.py for this simple project.
Step 3: Write the Python Code
from fastapi import FastAPI
from datetime import datetime
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to Cyber Supto Time API"}
@app.get("/current-time")
def current_time():
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
return {"current_time": current_time}
@app.get("/current-date")
def current_date():
today = datetime.today()
current_date = today.strftime("%Y-%m-%d")
return {"current_date": current_date}
@app.get("/current-datetime")
def current_datetime():
now = datetime.now()
dt = now.strftime("%Y-%m-%d %H:%M:%S")
return {"current_datetime": dt}
Step 4: Run the API Server
Run the API using Uvicorn:
uvicorn main:app --reload
Explanation:
mainrefers to main.pyapprefers to the FastAPI instance--reloadautomatically reloads the server when code changes
Step 5: Test Your API
Open your browser and visit:
http://127.0.0.1:8000/→ Welcome messagehttp://127.0.0.1:8000/current-time→ Current timehttp://127.0.0.1:8000/current-date→ Current datehttp://127.0.0.1:8000/current-datetime→ Date and time
Step 6: Optional – Test with Swagger UI
FastAPI comes with built-in API documentation. Open:
http://127.0.0.1:8000/docs
Here, you can test all API endpoints interactively.
Step 7: Making API Accessible Publicly
If you want your API accessible over the internet, you can use hosting platforms:
- PythonAnywhere
- Heroku
- Render
- Railway
Follow the platform instructions to deploy your FastAPI project.
Step 8: Improving Your API
You can extend your Time API with:
- Different timezones using
pytzlibrary - Return JSON in ISO format for easier integration
- Adding a query parameter to get time in a specific timezone
- Logging API requests
- Rate limiting for security
Example – Timezone Support
from fastapi import FastAPI
from datetime import datetime
import pytz
app = FastAPI()
@app.get("/time")
def get_time(timezone: str = "Asia/Dhaka"):
tz = pytz.timezone(timezone)
now = datetime.now(tz)
return {"time": now.strftime("%Y-%m-%d %H:%M:%S"), "timezone": timezone}
Test with URL: http://127.0.0.1:8000/time?timezone=Asia/Kolkata
Tips for Writing Efficient APIs in Python
- Use FastAPI for modern and high-performance APIs
- Keep endpoints simple and focused
- Use proper HTTP status codes
- Add validation for query parameters and input
- Use async endpoints for high performance
Conclusion
Creating a simple Time API in Python is easy and a great project for beginners. Using FastAPI, you can build fast, clean, and professional APIs with minimal code. By adding features like timezone support, async endpoints, and proper documentation, you can take your API to a professional level.
Thanks for reading,
Cyber Supto.
Post a Comment