Register Your Application and Obtain Access Token
- To interact with Instagram API, you first need to set up a Facebook Developer account and create an application to obtain an access token, which authenticates your requests. Follow the guidelines on the Meta for Developers page to register your app.
- Once your app is registered, you should get an access token from Instagram Graph API. Ensure that this token has the necessary permissions for the data you wish to access, specifically `instagram_graph_user_media` to display user photos.
Make API Calls to Fetch User Photos
- Use the access token to make requests to the Instagram Graph API. To get user photos, you will typically make a GET request to the `/me/media` endpoint.
- Here's an example of how you can use Python with the `requests` library to get the user's media data:
import requests
access_token = 'YOUR_ACCESS_TOKEN'
endpoint = 'https://graph.instagram.com/me/media?fields=id,caption,media_type,media_url,thumbnail_url,permalink&access_token=' + access_token
response = requests.get(endpoint)
user_media = response.json()
print(user_media)
Parse JSON Response and Filter For Photos
- The API response contains various types of user media, including videos and carousels. You might want to specifically filter out photos.
- You can iterate through the JSON response and pick the media items with `media_type` set to `IMAGE`:
for media in user_media['data']:
if media['media_type'] == 'IMAGE':
print(media['media_url'], media['caption'])
Display Photos on Your Website
- To display the photos on your website, integrate the parsed data into your HTML elements. Utilize JavaScript or a server-side language to dynamically generate the content.
- Here's a basic example of how you might display a list of photos using HTML and simple JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Instagram Photos</title>
</head>
<body>
<div id="instagram-photos"></div>
<script>
const photos = [
// Assume your Python script saved the media URLs and captions in a similar structure
{'url': 'https://example.com/photo1.jpg', 'caption': 'Photo 1'},
{'url': 'https://example.com/photo2.jpg', 'caption': 'Photo 2'},
];
const container = document.getElementById('instagram-photos');
photos.forEach(photo => {
const imgElement = document.createElement('img');
imgElement.src = photo.url;
imgElement.alt = photo.caption;
container.appendChild(imgElement);
});
</script>
</body>
</html>
- Ensure you consider security aspects such as token expiration and untrusted data handling to secure user interactions.
- Keep the website design responsive to cater to different device views, which can be efficiently achieved with CSS frameworks like Bootstrap.