| from fastapi import FastAPI, HTTPException |
| import instaloader |
| from pydantic import BaseModel |
| from typing import List |
| import os |
|
|
| app = FastAPI() |
|
|
| |
| class PostResponse(BaseModel): |
| caption: str |
| likes: int |
| comments: int |
| posted_on: str |
| image_url: str |
|
|
| |
| PROXY_URL = "http://p.webshare.io:5157:kknqfmqe:0wyvognccou8" |
|
|
| @app.get("/fetch-posts", response_model=List[PostResponse]) |
| async def fetch_instagram_posts(username: str, max_posts: int = 10): |
| """ |
| Fetch Instagram posts from a public profile using a proxy. |
| |
| Args: |
| username (str): The username of the Instagram profile. |
| max_posts (int): The maximum number of posts to fetch (default is 10). |
| |
| Returns: |
| List[PostResponse]: A list of posts with caption, likes, comments, posted_on, and image_url. |
| """ |
| |
| L = instaloader.Instaloader() |
| L.context.proxy = PROXY_URL |
|
|
| try: |
| |
| print(f"Fetching posts for user: {username}") |
| profile = instaloader.Profile.from_username(L.context, username) |
|
|
| |
| posts = [] |
|
|
| |
| count = 0 |
|
|
| |
| for post in profile.get_posts(): |
| post_data = { |
| "caption": post.caption or "No Caption", |
| "likes": post.likes, |
| "comments": post.comments, |
| "posted_on": post.date_utc.strftime("%Y-%m-%d %H:%M:%S"), |
| "image_url": post.url, |
| } |
| posts.append(post_data) |
|
|
| |
| count += 1 |
| if count >= max_posts: |
| break |
|
|
| print(f"\nFetched {count} posts for user: {username}.") |
| return posts |
|
|
| except instaloader.exceptions.ProfileNotExistsException: |
| raise HTTPException(status_code=404, detail=f"Profile '{username}' does not exist.") |
| except instaloader.exceptions.ConnectionException: |
| raise HTTPException(status_code=503, detail="Unable to connect to Instagram. Check your internet connection.") |
| except Exception as e: |
| raise HTTPException(status_code=500, detail=f"Unexpected error: {e}") |
|
|
| |
| if __name__ == "__main__": |
| import uvicorn |
| uvicorn.run(app, host="0.0.0.0", port=8000) |
|
|