File size: 2,451 Bytes
646fbf3
7c278df
646fbf3
ab8a00c
 
7c278df
646fbf3
 
 
 
 
 
 
 
 
 
ab8a00c
 
 
646fbf3
 
7c278df
ab8a00c
7c278df
 
 
646fbf3
7c278df
 
646fbf3
7c278df
ab8a00c
7c278df
ab8a00c
7c278df
 
 
 
 
 
646fbf3
 
 
7c278df
 
 
 
 
646fbf3
 
 
 
 
 
 
 
7c278df
 
 
 
 
 
 
646fbf3
7c278df
 
646fbf3
7c278df
646fbf3
7c278df
646fbf3
7c278df
646fbf3
7c278df
646fbf3
ab8a00c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from fastapi import FastAPI, HTTPException
import instaloader
from pydantic import BaseModel
from typing import List
import os

app = FastAPI()

# Pydantic model for the response
class PostResponse(BaseModel):
    caption: str
    likes: int
    comments: int
    posted_on: str
    image_url: str

# Define proxy settings (replace with your proxy details)
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.
    """
    # Initialize Instaloader with proxy configuration
    L = instaloader.Instaloader()
    L.context.proxy = PROXY_URL

    try:
        # Load the profile
        print(f"Fetching posts for user: {username}")
        profile = instaloader.Profile.from_username(L.context, username)

        # List to store posts
        posts = []

        # Counter to limit the number of posts
        count = 0

        # Loop through the posts
        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)

            # Increment the counter
            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}")

# Run the FastAPI app
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)