0
# API Access
1
2
Low-level Instagram API wrapper providing direct access to Instagram endpoints with minimal abstraction. The API class offers precise control over Instagram interactions without the automated behavior and filtering of the Bot class.
3
4
## Capabilities
5
6
### API Initialization and Authentication
7
8
Initialize and authenticate with Instagram's API endpoints using various configuration options.
9
10
```python { .api }
11
class API:
12
def __init__(self,
13
device=None,
14
base_path=current_path + "/config/",
15
save_logfile=True,
16
log_filename=None,
17
loglevel_file=logging.DEBUG,
18
loglevel_stream=logging.INFO):
19
"""
20
Initialize Instagram API wrapper.
21
22
Parameters:
23
- device: Device identifier from devices.py (defaults to None)
24
- base_path: Base path for configuration files (current_path + "/config/")
25
- save_logfile: Whether to save API logs to file (default True)
26
- log_filename: Custom log filename (default None)
27
- loglevel_file: Log level for file logging (default logging.DEBUG)
28
- loglevel_stream: Log level for console logging (default logging.INFO)
29
"""
30
31
def login(self,
32
username=None,
33
password=None,
34
force=False,
35
proxy=None,
36
use_cookie=True,
37
use_uuid=True,
38
cookie_fname=None,
39
ask_for_code=False,
40
set_device=True,
41
generate_all_uuids=True,
42
is_threaded=False):
43
"""
44
Authenticate with Instagram API.
45
46
Parameters:
47
- username: Instagram username
48
- password: Instagram password
49
- force: Force new login session
50
- proxy: Proxy server configuration
51
- use_cookie: Use saved cookies for authentication
52
- use_uuid: Generate/use UUID for session
53
- cookie_fname: Custom cookie filename
54
- ask_for_code: Prompt for 2FA code if needed
55
- set_device: Set device fingerprint
56
- generate_all_uuids: Generate all required UUIDs
57
- is_threaded: Whether running in threaded environment
58
59
Returns:
60
bool: True if login successful, False otherwise
61
"""
62
63
def logout(self):
64
"""
65
Logout from Instagram API session.
66
67
Returns:
68
bool: True if logout successful
69
"""
70
71
def two_factor_auth(self):
72
"""
73
Handle two-factor authentication challenge.
74
75
Returns:
76
bool: True if 2FA successful
77
"""
78
79
def solve_challenge(self):
80
"""
81
Solve Instagram security challenge.
82
83
Returns:
84
bool: True if challenge solved successfully
85
"""
86
```
87
88
### User Management Operations
89
90
Retrieve user information, manage followers/following relationships, and perform user-related actions.
91
92
```python { .api }
93
def get_user_followers(self, user_id, max_id=""):
94
"""
95
Retrieve user's followers list.
96
97
Parameters:
98
- user_id: Target user ID
99
- max_id: Pagination cursor for next page
100
101
Returns:
102
dict: Response containing followers list and pagination info
103
"""
104
105
def get_user_followings(self, user_id, max_id=""):
106
"""
107
Retrieve user's following list.
108
109
Parameters:
110
- user_id: Target user ID
111
- max_id: Pagination cursor for next page
112
113
Returns:
114
dict: Response containing following list and pagination info
115
"""
116
117
def get_username_info(self, user_id):
118
"""
119
Get detailed user information.
120
121
Parameters:
122
- user_id: Target user ID or username
123
124
Returns:
125
dict: User information including profile details, counts, and settings
126
"""
127
128
def get_self_username_info(self):
129
"""
130
Get current authenticated user's information.
131
132
Returns:
133
dict: Current user's profile information
134
"""
135
136
def follow(self, user_id):
137
"""
138
Follow a user.
139
140
Parameters:
141
- user_id: Target user ID
142
143
Returns:
144
dict: API response with follow status
145
"""
146
147
def unfollow(self, user_id):
148
"""
149
Unfollow a user.
150
151
Parameters:
152
- user_id: Target user ID
153
154
Returns:
155
dict: API response with unfollow status
156
"""
157
158
def block(self, user_id):
159
"""
160
Block a user.
161
162
Parameters:
163
- user_id: Target user ID
164
165
Returns:
166
dict: API response with block status
167
"""
168
169
def unblock(self, user_id):
170
"""
171
Unblock a user.
172
173
Parameters:
174
- user_id: Target user ID
175
176
Returns:
177
dict: API response with unblock status
178
"""
179
180
def remove_follower(self, user_id):
181
"""
182
Remove a follower.
183
184
Parameters:
185
- user_id: Follower user ID to remove
186
187
Returns:
188
dict: API response with removal status
189
"""
190
```
191
192
### Media Management Operations
193
194
Upload, download, and manage photos and videos with detailed control over metadata and options.
195
196
```python { .api }
197
def upload_photo(self,
198
photo,
199
caption=None,
200
upload_id=None,
201
from_video=False,
202
force_resize=False,
203
options={}):
204
"""
205
Upload photo to Instagram.
206
207
Parameters:
208
- photo: Photo file path or data
209
- caption: Photo caption text
210
- upload_id: Custom upload identifier
211
- from_video: Whether photo is extracted from video
212
- force_resize: Force photo resizing
213
- options: Additional upload options
214
215
Returns:
216
dict: Upload response with media information
217
"""
218
219
def download_photo(self, media_id, filename, media=False, folder="photos"):
220
"""
221
Download photo from Instagram.
222
223
Parameters:
224
- media_id: Instagram media ID
225
- filename: Download filename
226
- media: Media object instead of ID
227
- folder: Download folder path
228
229
Returns:
230
bool: True if download successful
231
"""
232
233
def upload_video(self,
234
video,
235
caption=None,
236
upload_id=None,
237
thumbnail=None,
238
options={}):
239
"""
240
Upload video to Instagram.
241
242
Parameters:
243
- video: Video file path
244
- caption: Video caption text
245
- upload_id: Custom upload identifier
246
- thumbnail: Thumbnail image path
247
- options: Additional upload options
248
249
Returns:
250
dict: Upload response with media information
251
"""
252
253
def download_video(self, media_id, filename, media=False, folder="video"):
254
"""
255
Download video from Instagram.
256
257
Parameters:
258
- media_id: Instagram media ID
259
- filename: Download filename
260
- media: Media object instead of ID
261
- folder: Download folder path
262
263
Returns:
264
bool: True if download successful
265
"""
266
267
def media_info(self, media_id):
268
"""
269
Get detailed media information.
270
271
Parameters:
272
- media_id: Instagram media ID
273
274
Returns:
275
dict: Media information including URLs, dimensions, user data
276
"""
277
278
def delete_media(self, media):
279
"""
280
Delete media post.
281
282
Parameters:
283
- media: Media object or media ID
284
285
Returns:
286
dict: Deletion response
287
"""
288
289
def archive_media(self, media, undo=False):
290
"""
291
Archive or unarchive media post.
292
293
Parameters:
294
- media: Media object or media ID
295
- undo: Unarchive if True, archive if False
296
297
Returns:
298
dict: Archive operation response
299
"""
300
```
301
302
### Interaction Operations
303
304
Perform likes, comments, and other engagement actions with detailed tracking parameters.
305
306
```python { .api }
307
def like(self,
308
media_id,
309
double_tap=None,
310
container_module="feed_short_url",
311
feed_position=0,
312
username=None,
313
user_id=None,
314
hashtag_name=None,
315
hashtag_id=None,
316
entity_page_name=None,
317
entity_page_id=None):
318
"""
319
Like a media post with detailed tracking.
320
321
Parameters:
322
- media_id: Instagram media ID
323
- double_tap: Double tap like indicator
324
- container_module: Source module for analytics
325
- feed_position: Position in feed for analytics
326
- username: Username for context tracking
327
- user_id: User ID for context tracking
328
- hashtag_name: Hashtag context
329
- hashtag_id: Hashtag ID for context
330
- entity_page_name: Entity page context
331
- entity_page_id: Entity page ID
332
333
Returns:
334
dict: Like operation response
335
"""
336
337
def unlike(self, media_id):
338
"""
339
Unlike a media post.
340
341
Parameters:
342
- media_id: Instagram media ID
343
344
Returns:
345
dict: Unlike operation response
346
"""
347
348
def comment(self, media_id, comment_text):
349
"""
350
Comment on a media post.
351
352
Parameters:
353
- media_id: Instagram media ID
354
- comment_text: Comment content
355
356
Returns:
357
dict: Comment operation response with comment ID
358
"""
359
360
def reply_to_comment(self, media_id, comment_text, parent_comment_id):
361
"""
362
Reply to an existing comment.
363
364
Parameters:
365
- media_id: Instagram media ID
366
- comment_text: Reply content
367
- parent_comment_id: ID of comment being replied to
368
369
Returns:
370
dict: Reply operation response
371
"""
372
373
def delete_comment(self, media_id, comment_id):
374
"""
375
Delete a comment.
376
377
Parameters:
378
- media_id: Instagram media ID
379
- comment_id: Comment ID to delete
380
381
Returns:
382
dict: Delete operation response
383
"""
384
```
385
386
### Feed Operations
387
388
Access various Instagram feeds including timeline, user feeds, hashtag feeds, and location-based content.
389
390
```python { .api }
391
def get_timeline_feed(self, options=[]):
392
"""
393
Get user's timeline feed.
394
395
Parameters:
396
- options: Additional feed options
397
398
Returns:
399
dict: Timeline feed response with media items
400
"""
401
402
def get_user_feed(self, user_id, max_id="", min_timestamp=None):
403
"""
404
Get specific user's media feed.
405
406
Parameters:
407
- user_id: Target user ID
408
- max_id: Pagination cursor
409
- min_timestamp: Minimum timestamp for posts
410
411
Returns:
412
dict: User feed response with media items and pagination
413
"""
414
415
def get_hashtag_feed(self, hashtag, max_id=""):
416
"""
417
Get hashtag feed.
418
419
Parameters:
420
- hashtag: Hashtag name (without #)
421
- max_id: Pagination cursor
422
423
Returns:
424
dict: Hashtag feed response with media items
425
"""
426
427
def get_location_feed(self, location_id, max_id=""):
428
"""
429
Get location-based feed.
430
431
Parameters:
432
- location_id: Instagram location ID
433
- max_id: Pagination cursor
434
435
Returns:
436
dict: Location feed response with media items
437
"""
438
439
def get_liked_media(self, max_id=""):
440
"""
441
Get user's liked media.
442
443
Parameters:
444
- max_id: Pagination cursor
445
446
Returns:
447
dict: Liked media response with items and pagination
448
"""
449
```
450
451
### Story Operations
452
453
Upload, download, and manage Instagram Stories content.
454
455
```python { .api }
456
def upload_story_photo(self, photo, upload_id=None):
457
"""
458
Upload photo to Instagram Story.
459
460
Parameters:
461
- photo: Photo file path
462
- upload_id: Custom upload identifier
463
464
Returns:
465
dict: Story upload response
466
"""
467
468
def download_story(self, filename, story_url, username):
469
"""
470
Download story content.
471
472
Parameters:
473
- filename: Download filename
474
- story_url: Story media URL
475
- username: Story owner username
476
477
Returns:
478
bool: True if download successful
479
"""
480
481
def get_user_reel(self, user_id):
482
"""
483
Get user's story reel.
484
485
Parameters:
486
- user_id: Target user ID
487
488
Returns:
489
dict: User reel response with story items
490
"""
491
```
492
493
### Direct Message Operations
494
495
Send and manage direct messages and message threads.
496
497
```python { .api }
498
def send_direct_item(self, item_type, users, **options):
499
"""
500
Send direct message item.
501
502
Parameters:
503
- item_type: Type of message item ("text", "media", etc.)
504
- users: List of recipient user IDs
505
- **options: Additional message options (text content, media_id, etc.)
506
507
Returns:
508
dict: Send message response
509
"""
510
511
def get_direct_v2_inbox(self):
512
"""
513
Get direct message inbox.
514
515
Returns:
516
dict: Inbox response with message threads
517
"""
518
519
def get_thread(self, thread_id, cursor_id=None):
520
"""
521
Get direct message thread.
522
523
Parameters:
524
- thread_id: Message thread ID
525
- cursor_id: Pagination cursor
526
527
Returns:
528
dict: Thread response with messages
529
"""
530
```
531
532
### Search Operations
533
534
Search for users, hashtags, and locations across Instagram.
535
536
```python { .api }
537
def search_users(self, query):
538
"""
539
Search for users by query.
540
541
Parameters:
542
- query: Search query string
543
544
Returns:
545
dict: Search results with user list
546
"""
547
548
def search_tags(self, query):
549
"""
550
Search for hashtags by query.
551
552
Parameters:
553
- query: Hashtag search query
554
555
Returns:
556
dict: Search results with hashtag list
557
"""
558
559
def search_location(self, query="", lat=None, lng=None):
560
"""
561
Search for locations by query or coordinates.
562
563
Parameters:
564
- query: Location search query
565
- lat: Latitude coordinate
566
- lng: Longitude coordinate
567
568
Returns:
569
dict: Search results with location list
570
"""
571
572
def fb_user_search(self, query):
573
"""
574
Search Facebook users connected to Instagram.
575
576
Parameters:
577
- query: Search query string
578
579
Returns:
580
dict: Facebook user search results
581
"""
582
```
583
584
### API Properties and State
585
586
Access current session state and configuration information.
587
588
```python { .api }
589
@property
590
def user_id(self):
591
"""Current authenticated user ID"""
592
593
@property
594
def username(self):
595
"""Current authenticated username"""
596
597
@property
598
def cookie_dict(self):
599
"""Session cookie dictionary"""
600
601
@property
602
def token(self):
603
"""CSRF token for API requests"""
604
605
@property
606
def rank_token(self):
607
"""Rank token for API requests"""
608
```
609
610
## Usage Examples
611
612
### Basic API Usage
613
614
```python
615
from instabot import API
616
617
# Initialize API
618
api = API(save_logfile=True, loglevel_stream=logging.INFO)
619
620
# Login
621
success = api.login(username="your_username", password="your_password")
622
if not success:
623
print("Login failed")
624
exit()
625
626
# Get user information
627
user_info = api.get_username_info("target_user")
628
print(f"User: {user_info['user']['username']}")
629
print(f"Followers: {user_info['user']['follower_count']}")
630
631
# Upload a photo
632
result = api.upload_photo("photo.jpg", caption="Hello Instagram!")
633
if result:
634
print("Photo uploaded successfully")
635
636
# Like some media
637
media_info = api.get_user_feed("target_user")
638
for media in media_info['items'][:3]:
639
api.like(media['id'])
640
print(f"Liked media: {media['id']}")
641
642
# Logout
643
api.logout()
644
```
645
646
### Advanced API Operations
647
648
```python
649
from instabot import API
650
import logging
651
652
# Initialize with custom configuration
653
api = API(
654
device="samsung_galaxy_s9_plus",
655
save_logfile=True,
656
log_filename="my_api.log",
657
loglevel_file=logging.DEBUG
658
)
659
660
# Login with advanced options
661
api.login(
662
username="advanced_user",
663
password="secure_password",
664
use_cookie=True,
665
generate_all_uuids=True
666
)
667
668
# Complex feed operations
669
hashtag_feed = api.get_hashtag_feed("photography", max_id="")
670
for media in hashtag_feed['items'][:10]:
671
# Get detailed media info
672
media_details = api.media_info(media['id'])
673
674
# Like with tracking parameters
675
api.like(
676
media['id'],
677
container_module="hashtag_feed",
678
hashtag_name="photography",
679
username=media['user']['username']
680
)
681
682
# Comment on selected posts
683
if media['like_count'] > 100:
684
api.comment(media['id'], "Amazing shot! 📸")
685
686
# Direct message operations
687
inbox = api.get_direct_v2_inbox()
688
for thread in inbox['inbox']['threads'][:5]:
689
thread_details = api.get_thread(thread['thread_id'])
690
print(f"Thread with: {thread['users'][0]['username']}")
691
692
# Search operations
693
user_results = api.search_users("photographer")
694
for user in user_results['users'][:10]:
695
user_info = api.get_username_info(user['pk'])
696
if user_info['user']['follower_count'] > 1000:
697
api.follow(user['pk'])
698
699
api.logout()
700
```