The post Send Email Using Python appeared first on PythonForBeginners.com.
]]>In this article, we will use Simple Mail Transfer Protocol (SMTP) to send emails using python. For this, we will use the smtplib module. Also, we will use a gmail.com email id to send the email. We need to specify the mailing platform because different mailing platforms use different port numbers to send the email. Therefore, we need to know the port number used by the mail service providers for sending the email using python.
Suggested Reading: Create Chat Application in Python
For sending the mail using the smtplib module, we will follow the following steps.
Following is the code to send email using python.
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
email_id="[email protected]" #your email
password= "*********" password of gmail account
s.login("email_id", "password")
message= "Email Body"
s.sendmail("email_id", "receiver_email_id", message)
s.quit()
In this article, we have discussed how to send email using python. To learn more about python programming, you can read this article on dictionary comprehension in python. You might like this article on list comprehension in python too.
The post Send Email Using Python appeared first on PythonForBeginners.com.
]]>The post Scraping Wunderground appeared first on PythonForBeginners.com.
]]>Working with APIs is both fun and educational.
Many companies like Google, Reddit and Twitter releases it’s API to the public
so that developers can develop products that are powered by its service.
Working with APIs learns you the nuts and bolts beneath the hood.
In this post, we will work the Weather Underground API.
We will build an app that will connect to ‘Wunderground‘ and retrieve.
Weather Forecasts etc.
Wunderground provides local & long range Weather Forecast, weather reports,
maps & tropical weather conditions for locations worldwide.
An API is a protocol intended to be used as an interface by software components
to communicate with each other. An API is a set of programming instructions and
standards for accessing web based software applications (such as above).
With API’s applications talk to each other without any user knowledge or
intervention.
The first thing that we need to do when we want to use an API, is to see if the
company provides any API documentation. Since we want to write an application for
Wunderground, we will go to Wundergrounds website
At the bottom of the page, you should see the “Weather API for Developers”.
Most of the API features require an API key, so let’s go ahead and sign up for
a key before we start to use the Weather API.
In the documentation we can also read that the API requests are made over HTTP
and that Data features return JSON or XML.
To read the full API documentation, see this link.
Before we get the key, we need to first create a free account.
Next step is to sign up for the API key. Just fill in your name, email address,
project name and website and you should be ready to go.
Many services on the Internet (such as Twitter, Facebook..) requires that you
have an “API Key”.
An application programming interface key (API key) is a code passed in by
computer programs calling an API to identify the calling program, its developer,
or its user to the Web site.
API keys are used to track and control how the API is being used, for example
to prevent malicious use or abuse of the API.
The API key often acts as both a unique identifier and a secret token for
authentication, and will generally have a set of access rights on the API
associated with it.
Wunderground provides an example for us in their API documentation.
Current Conditions in US City
http://api.wunderground.com/api/0def10027afaebb7/conditions/q/CA/San_Francisco.json
If you click on the “Show response” button or copy and paste that URL into your
browser, you should something similar to this:
{
"response": {
"version": "0.1"
,"termsofService": "http://www.wunderground.com/weather/api/d/terms.html"
,"features": {
"conditions": 1
}
}
, "current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"San Francisco, CA",
"city":"San Francisco",
"state":"CA",
"state_name":"California",
"country":"US",
"country_iso3166":"US",
"zip":"94101",
"magic":"1",
"wmo":"99999",
"latitude":"37.77500916",
"longitude":"-122.41825867",
"elevation":"47.00000000"
},
.....
On the “Code Samples” page we can see the whole Python code to retrieve the
current temperature in Cedar Rapids.
Copy and paste this into your favorite editor and save it as anything you like.
Note, that you have to replace “0def10027afaebb7” with your own API key.
import urllib2
import json
f = urllib2.urlopen('http://api.wunderground.com/api/0def10027afaebb7/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in %s is: %s" % (location, temp_f)
f.close()
To run the program in your terminal:
python get_current_temp.py
Your program will return the current temperature in Cedar Rapids:
Current temperature in Cedar Rapids is: 68.9
Now that we have looked at and tested the examples provided by Wunderground,
let’s create a program by ourselves.
The Weather Underground provides us with a whole bunch of “Data Features” that
we can use.
It is important that you read through the information there, to understand how
the different features can be accessed.
“Most API features can be accessed using the following format.
Note that several features can be combined into a single request.”
http://api.wunderground.com/api/0def10027afaebb7/features/settings/q/query.format
where:
0def10027afaebb7: Your API key
features: One or more of the following data features
settings (optional): Example: lang:FR/pws:0
query: The location for which you want weather information
format: json, or xml
What I want to do is to retrieve the forecast for Paris.
The forecast feature returns a summary of the weather for the next 3 days.
This includes high and low temperatures, a string text forecast and the conditions.
To retrieve the forecast for Paris, I will first have to find out the country
code for France, which I can find here:
Next step is to look for the “Feature: forecast” in the API documentation.
The string that we need can be found here:
http://www.wunderground.com/weather/api/d/docs?d=data/forecast
By reading the documentation, we should be able to construct an URL.
We now have the URL that we need and we can start with our program.
Now its time to make the API call to Weather Underground.
Note: Instead of using the urllib2 module as we did in the examples above,
we will in this program use the “requests” module.
Making the API call is very easy with the “requests” module.
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
Now, we have a Response object called “r”. We can get all the information we need
from this object.
Open your editor of choice, at the first line, import the requests module.
Note, the requests module comes with a built-in JSON decoder, which we can use
for the JSON data. That also means, that we don’t have to import the JSON
module (like we did in the previous example when we used the urllib2 module)
import requests
To begin extracting the information that we need, we first have to see
what keys that the “r” object returns to us.
The code below will return the keys and should return [u’response’, u’forecast’]
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data.keys()
Copy and paste the URL (from above) into a JSON editor.
I use http://jsoneditoronline.org/ but any JSON editor should do the work.
This will show an easier overview of all the data.
http://api.wunderground.com/api/your_api_key/forecast/q/France/Paris.json
Note, the same information can be gained via the terminal, by typing:
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
print r.text
After inspecting the output given to us, we can see that the data that we are
interested in, is in the “forecast” key. Back to our program, and print out the
data from that key.
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data['forecast']
The result is stored in the variable “data”.
To access our JSON data, we simple use the bracket notation, like this:
data[‘key’].
Let’s navigate a bit more through the data, by adding ‘simpleforecast’
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data['forecast']['simpleforecast']
We are still getting a bit to much output, but hold on, we are almost there.
The last step in our program is to add [‘forecastday’] and instead of printing
out each and every entry, we will use a for loop to iterate through the dictionary.
We can access anything we want like this, just look up what data you are
interested in.
In this program I wanted to get the forecast for Paris.
Let’s see how the code looks like.
import requests
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/France/Paris.json")
data = r.json()
for day in data['forecast']['simpleforecast']['forecastday']:
print day['date']['weekday'] + ":"
print "Conditions: ", day['conditions']
print "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C", '
'
Run the program.
$ python get_temp_paris.py
Monday:
Conditions: Partly Cloudy
High: 23C Low: 10C
Tuesday:
Conditions: Partly Cloudy
High: 23C Low: 10C
Wednesday:
Conditions: Partly Cloudy
High: 24C Low: 14C
Thursday:
Conditions: Mostly Cloudy
High: 26C Low: 15C
The forecast feature is just one of many. I will leave it up to you to explore
the rest.
Once you get the understanding of an API and it’s output in JSON, you understand
how most of them work.
A comprehensive list of Python APIs
Weather Underground
The post Scraping Wunderground appeared first on PythonForBeginners.com.
]]>The post List of Python API’s appeared first on PythonForBeginners.com.
]]>Many Internet companies, such as Facebook, Google, and Twitter provides Application Programming Interfaces (or API’s) that you can use to build your own applications. An API is a set of programming instructions and standards for accessing web based software applications. A wrapper is an API client, that are commonly used to wrap the API into easy to use functions by doing the API calls itself. This page provides you with a list of python API’s, but also a link to its Python wrapper.
Amazon Web Services is a collection of remote computing services that together make up a cloud computing platform, offered over the Internet by Amazon.com
Bing is a search engine that brings together the best of search and people in your social networks to help you spend less time searching and more time doing.
URL shortening and bookmarking service
Blog-publishing service
Online file sharing and Cloud content management service for enterprise companies.
Keep, share, and discover the best of the Web using Delicious, the world’s leading social bookmarking service.
Free service that lets you bring your photos, docs, and videos anywhere and share them easily
Facebook is an online social networking service.
Foursquare is a location-based social networking website for mobile devices, such as smartphones
Online auction and shopping website
Image hosting and video hosting website
A Geocoding Toolbox for Python. Official git repo.
Google Maps is a web mapping service application and technology provided by Google
Simple Image Sharer
Search engine for jobs
Online photo-sharing, video-sharing and social networking service that enables its users to take pictures and videos
The world’s largest online music catalogue, powered by your scrobbles.
World’s Largest Professional Network
Cloud- based log management service
On-demand Internet streaming media
IT alert monitoring
Cloud- based log management service
Pinterest is a pinboard-style photo-sharing website that allows users to create and manage theme-based image collections such as events, interests, and hobbies.
A social news and entertainment website where registered users submit content in the form of either a link or a text post
Film review aggregator
Share your sounds
Commercial music streaming service
Technorati is an Internet search engine for searching blogs.
Twitter is an online social networking service and microblogging service that enables its users to send and read text-based messages of up to 140 characters, known as tweets
Tumblr, stylized in their logo as tumblr., is a microblogging platform and social networking website
Wikipedia is a free, web-based, collaborative, multilingual encyclopedia project supported by the non-profit Wikimedia Foundation.
Web portal, search engine Yahoo! Search, and related services, including Yahoo! Directory, Yahoo! Mail, Yahoo!
Local search website
YouTube is a video-sharing website
Is a social news website focusing on computer science and entrepreneurship.
Wunderground
How To Access Various Web Services in Python
The post List of Python API’s appeared first on PythonForBeginners.com.
]]>The post How to use the Hacker News API appeared first on PythonForBeginners.com.
]]>Today I will go through the “Unofficial Python API for Hacker News”, which can be found here
Hacker News is a social news website that caters to programmers and entrepreneurs, delivering content related to computer science and entrepreneurship. [source]
In the How to use Reddit API in Python, we described how to directly access Reddit API directly. Another way of doing that would be to use one of the Reddit wrappers. A wrapper is an API client, that are commonly used to wrap the API into easy to use functions by doing the API calls itself. When using a wrapper, you don’t have to care what’s going on behind the scenes, which sometimes can be easier for a beginner. Think of it as a interface between python and a web service.
Let’s get started and install it by using the pip tool.
pip search HackerNews
HackerNews - Python API for Hacker News.
pip install HackerNews
Successfully installed HackerNews Cleaning up… pip show HackerNews — Name: HackerNews Version: 1.3.3 Location: /usr/local/lib/python2.7/dist-packages Requires: BeautifulSoup4
It is suggested that you read the documentation, which is available on this Github page. The API contains a few classes (HN and Story). The classes provides you with methods. The available methods for the HN class are: get_top_stories() Returns a list of Story objects from the homepage of HN get_newest_stories() Returns a list of Story objects from the newest page of HN The available method for the Story class is: print_story() – Print the details of a story
The author of the API provides an example on his Github page. The example prints top and new posts from Hacker news. Open your favorite editor and copy and paste the following code.
#!/usr/bin/env python
from hn import HN
hn = HN()
# print top 10 stories from homepage
for story in hn.get_top_stories()[:10]:
story.print_story()
print '*' * 50
print ''
# print 10 latest stories
for story in hn.get_newest_stories()[:10]:
story.print_story()
print '*' * 50
print ''
# print all self posts from the homepage
for story in hn.get_top_stories():
if story.is_self_post:
story.print_story()
print '*' * 50
print ''
Save it as test_bot.py and run it. The program will loop through every story (post) on hacker news and give you the top 10 latest stories. For every post it will show information seen below Story details rank – the rank of story on the page story_id – the story’s id title – the title of the story is_self_post – true for self/job stories link – the url it points to (None for self posts) domain – the domain of the link (None for self posts) points – the points/karma on the story submitter – the user who submitted the story submitter_link – the above user profile link published_time – the published time ago num_comments – the number of comments it has comments_link – the link to the comments page Using a python wrapper for an API is nice and simple, but try to understand whats going on behind the scenes. It is important that you understand what is going on in the code, and once you learned it, you can go for wrapper. Try to get knowledge about Json and API’s, to understand how most of them work.
The post How to use the Hacker News API appeared first on PythonForBeginners.com.
]]>The post How to use Reddit API in Python appeared first on PythonForBeginners.com.
]]>In an earlier post “How to access various Web Services in Python“, we described
how we can access services such as YouTube, Vimeo and Twitter via their API’s.
Note, there are a few Reddit Wrappers that you can use to interact with Reddit.
A wrapper is an API client, that are commonly used to wrap the API into easy to
use functions by doing the API calls itself.
That results in that the user of it can be less concerned with how the code
actually works.
If you don’t use a wrapper, you will have to access the Reddits API directly,
which is exactly what we will do in this post.
Since we are going to focus on the API from Reddit, let’s head over to their API
documentation. I recommend that you get familiar with the documentation and also
pay extra attention to the the overview and the sections about “modhashes”,
“fullnames” and “type prefixes”.
The result from the API will return as either XML or JSON. In this post we will
use the JSON format.
Please refer to above post or the official documentation for more information
about the JSON structure.
In the API documentation, you can see there are tons of things to do.
In this post, we have chosen to extract information from our own Reddit account.
The information we need for that is: GET /user/username/where[ .json | .xml ]
GET /user/username/where[ .json | .xml ]
? /user/username/overview
? /user/username/submitted
? /user/username/comments
? /user/username/liked
? /user/username/disliked
? /user/username/hidden
? /user/username/saved
If we for example want to use “comments”, the URL would be:
http://www.reddit.com/user/spilcm/comments/.json
You can see that we have replaced “username” and “where” with our own input.
To see the data response, you can either make a curl request, like this:
curl http://www.reddit.com/user/spilcm/comments/.json
…or just paste the URL into your browser.
You can see that the response is JSON. This may be difficult to look at in the
browser, unless you have the JSONView plugin installed.
These extensions are available for Firefox and Chrome.
Now that we have the URL, let’s start to do some coding.
Open up your favourite IDLE / Editor and import the modules that we will need.
Importing the modules. The pprint and json modules are optional.
from pprint import pprint
import requests
import json
Now its time to make the API call to Reddit.
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
Now, we have a Response object called “r”. We can get all the information we need
from this object.
The Requests module comes with a builtin JSON decoder, which we can use for with
the JSON data.
As you could see on the image above, the output that we get is not really what we
want to display.
The question is, how do we extract useful data from it?
If we just want to look at the keys in the “r” object:
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
data = r.json()
print data.keys()
That should give us the following output:
[u’kind’, u’data’]
These keys are very important to us.
Now its time to get the data that we are interested in.
Get the JSON feed and copy/paste the output into a JSON editor to get an easier
overview over the data.
An easy way of doing that is to paste JSON result into an online JSON editor.
I use http://jsoneditoronline.org/ but any JSON editor should do the work.
Let’s see an example of this:
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
As you can see from the image, we get the same keys (kind, data) as we did before
when we printed the keys.
Let’s convert the JSON data into Python dictionary.
You can do that like this:
r.json()
#OR
json.loads(r.text)
Now when we have a Python dictionary, we start using it to get the the results
we want.
Just navigate your way down until you find what you’re after.
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
data = r.json()
print data['data']['children'][0]
The result is stored in the variable “data”.
To access our JSON data, we simple use the bracket notation, like this:
data[‘key’].
Remember that an array is indexed from zero.
Instead of printing each and every entry, we can use a for loop to iterate
through our dictionary.
for child in data['data']['children']:
print child['data']['id'], "
", child['data']['author'],child['data']['body']
print
We can access anything we want like this, just look up what data you are
interested in.
As you can see in our complete script, we only have to import one module:
(requests)
import requests
r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json')
r.text
data = r.json()
for child in data['data']['children']:
print child['data']['id'], "
", child['data']['author'],child['data']['body']
print
When you run the script, you should see something similar to this:
http://docs.python-requests.org/en/latest/
The post How to use Reddit API in Python appeared first on PythonForBeginners.com.
]]>The post Python API and JSON appeared first on PythonForBeginners.com.
]]>An application programming interface (API) is a protocol intended to be used as an interface by software components to communicate with each other. It’s basically a set of programming instructions and standards for accessing a Web-based software application or Web tool. A software company (like Amazon, Google etc) releases its API to the public so that other software developers can design products that are powered by its service. For a more extended explanation on API, read this excellent article from howstuffworks.com.
It is important to know that an API is a software-to-software interface, not a user interface. With APIs, applications talk to each other without any user knowledge or intervention. When we want to interact with an API in Python (like accessing web services), we get the responses in a form called JSON. To interact with JSON, we can use the json and simplejson modules. JSON (JavaScript Object Notation) is a compact, text based format for computers to exchange data and is once loaded into Python just like a dictionary. JSON data structures map directly to Python data types, which makes this a powerful tool for directly accessing data without having to write any XML parsing code.
Let’s show how we can do this by using Twittes API. The first thing you have to do, is to find an URL to call the API. The next step is to import the modules that we need.
import json
import urllib2
# open the url and the screen name
# (The screen name is the screen name of the user for whom to return results for)
url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=python"
# this takes a python object and dumps it to a string which is a JSON
# representation of that object
data = json.load(urllib2.urlopen(url))
# print the result
print data
http://money.howstuffworks.com/business-communications/how-to-leverage-an-api-for-conferencing1.htm
The post Python API and JSON appeared first on PythonForBeginners.com.
]]>The post Using the YouTube API in Python appeared first on PythonForBeginners.com.
]]>In this post we will be looking on how to use the YouTube API in Python. This program will show how we can use the API to retrieve feeds from YouTube. This particular script will show the most popular videos on YouTube right now.
Some of the most popular YouTube feeds are: most_recent most_viewed top_rated most_discussed top_favorites most_linked recently_featured most_responded
To start getting the data that we want from the YouTube feeds, we begin by importing the necessary modules.
import requests
import json
We make it a bit “prettier” by printing out what the program does. Then we get the feed by using the requests module. I used to use the urllib2 module to open the URL, but ever since Kenneth Reitz gave us the Requests module, I’m letting that module do most of my HTTP tasks.
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
After we have got the feed and saved it to the variable “r”, we convert it into a Python dictionary.
data = json.loads(r.text)
Now, we have a use a for loop to go through the data
for item in data['data']['items']:
This can sometimes be the tricky part and you need to look carefully how the structure is presented to you. Using a JSON editor will make it easier.
This script will show the most popular videos on YouTube.
# Import the modules
import requests
import json
# Make it a bit prettier..
print "-" * 30
print "This will show the Most Popular Videos on YouTube"
print "-" * 30
# Get the feed
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
# Convert it to a Python dictionary
data = json.loads(r.text)
# Loop through the result.
for item in data['data']['items']:
print "Video Title: %s" % (item['title'])
print "Video Category: %s" % (item['category'])
print "Video ID: %s" % (item['id'])
print "Video Rating: %f" % (item['rating'])
print "Embed URL: %s" % (item['player']['default'])
print
Using string formatting makes it a lot easier to view the code.
# Sample Output ------------------------------ This will show the Most Popular Videos on YouTube ------------------------------ Video Title: PSY - GANGNAM STYLE (?????) M/V Video Category: Music Video ID: 9bZkp7q19f0 Video Rating: 4.614460 Embed URL: http://www.youtube.com/watch?v=9bZkp7q19f0&feature=youtube_gdata_player Video Title: PSY - GENTLEMAN M/V Video Category: Music Video ID: ASO_zypdnsQ Video Rating: 4.372500 Embed URL: http://www.youtube.com/watch?v=ASO_zypdnsQ&feature=youtube_gdata_player Video Title: MACKLEMORE & RYAN LEWIS - THRIFT SHOP FEAT. WANZ (OFFICIAL VIDEO) Video Category: Music Video ID: QK8mJJJvaes Video Rating: 4.857624 Embed URL: http://www.youtube.com/watch?v=QK8mJJJvaes&feature=youtube_gdata_player
To use another YouTube standard feed, simple replace the feed in the URL: http://gdata.youtube.com/feeds/api/standardfeeds/most_responded?v=2&alt=jsonc You may have to modify the script to get the expected result.
The post Using the YouTube API in Python appeared first on PythonForBeginners.com.
]]>The post How to use the Vimeo API in Python appeared first on PythonForBeginners.com.
]]>
In this post we will be looking on how to use the Vimeo API in Python.
Vimeo offers an API which lets us integrate with their site and build applications
on top of their data.
Vimeo provides a "Simple API" and an "Advanced API".
To perform authenticated read/write requests on videos, users, groups, channels,
albums, or upload, you will have to use the Advanced API.
It uses OAuth for authentication, so you will first need to sign up.
When using the Simple API, you don’t need to register or authenticate your app.
One of the drawback with using the Simple API is that it’s limited to public data
and is read-only.
The response limits in the Simple API include up to 20 items per page.
Vimeos API provides different Response formats, and they all return the exact
same data.
After looking at the website of Vimeo, I found out that I can start out with this
URL: http://vimeo.com/api/v2/video/video_id.output
the video_id is the ID of the video you want information for.
the output specifies which type that we want (json, xml)
Making a User Request
Making a Video Request
Making an Activity Request
Making a Group Request
Making a Channel Request
Making an Album Request
This script will show how you can set up the script to make a Video request from
Vimeo.
import requests
import json
r = requests.get("http://vimeo.com/api/v2/video/48082757.json")
r.text
data = json.loads(r.text)
'do something with the data'
Vimeo has been kind enough to provide some API examples for us which can be found
on their GitHub repository. https://github.com/vimeo/vimeo-api-examples
http://developer.vimeo.com/apis/
The post How to use the Vimeo API in Python appeared first on PythonForBeginners.com.
]]>