Overview | Intro | Anatomy | Play | Ideation | Sign-Up | Login | Profile | Style | Deploy | Scrum |
Flask Apis
Categories: Python Flask Breadcrumb: /Introduction to APIs and how to use them with flask + activity
What Is an API?
API stands for Application Programming Interface. It’s a set of rules that lets two software programs talk to each other.
Simple Definition:
An API is like a menu in a restaurant. The menu shows you what you can order (the endpoints).You don’t need to know how the kitchen works — you just order. The kitchen prepares your food and sends it back.
In tech terms: You (frontend or Postman) send a request to the API. The backend (Flask, Django, Node, etc.) handles it and responds with data.
Example Task | API Being Used |
---|---|
Check weather on your phone | Weather API (e.g., OpenWeatherMap) |
Log in to a website | Authentication API |
Use Google Maps in an app | Google Maps API |
Submit a form on a website | Custom backend API (like your Flask app) |
✅ Where to Add New Functionality (Like a Weather API Call) Let’s say you want to add a new /weather route that calls an external weather API.
📌 You should add this logic to: /api/weather.py – create this new file if it doesn’t exist yet.
Then, define your route inside that file:
# /api/weather.py
import requests
from flask import Blueprint, request, jsonify
weather_api = Blueprint('weather_api', __name__)
API_KEY = 'abcd1234apikey'
@weather_api.route('/weather', methods=['GET'])
def get_weather():
city = request.args.get('city', 'San Diego')
url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric'
response = requests.get(url)
if response.status_code != 200:
return {'error': 'API request failed'}, response.status_code
data = response.json()
return jsonify({
'city': city,
'temperature': data['main']['temp'],
'description': data['weather'][0]['description']
})
🧠 Notes: External API logic goes into api/, not models/ (because you’re not storing or managing your own database table for this data).
Use a Blueprint so it plugs into the rest of the app cleanly.
⚙️ Don’t Forget to Register the Route Open your init.py and import/register your new Blueprint:
# __init__.py
from flask import Flask
from api.weather import weather_api # 👈 import your new route
def create_app():
app = Flask(__name__)
# Register blueprints
app.register_blueprint(weather_api)
return app