Python is one of the most popular programming languages because of its simple syntax. It is among the most popular programming languages for building RESTful APIs.
Here we'll use the Python web development framework Flask to build RESTful APIs. If you are new to Flask then don't worry we will also cover some of the basics of Flask.
What is Flask?
Flask is a python framework that is used to build web applications. It gives developers complete control over how users access data. Flask is a micro-framework based on Werkzeug's WSGI toolkit and Jinja templating engine.
Flask is one of the most popular frameworks of python for web development and popular sites like Netflix, Disqus, Linkedin, etc use the Flask framework.
Set up a Flask Application:
Before we start actual coding first we have to set up a Flask Application. It is very easy to set up the Flask application. Follow the following steps to use Flask:
$ mkdir flask-application
$ touch application.py
$ python3 -m venv env
$ source env/bin/activate
$ pip3 install flask-restful
Import the Flask Module:
Next, the most important step is to import the flask module and other important modules into our app.py python file.
Run the APP:
from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Quotes(Resource):
def get(self):
return {
'Name': {
'fullName': ['Manoj',
'Kumawat']
},
'Note': {
'message': ['This is my first message.']
}
}
api.add_resource(Quotes, '/')
if __name__ == '__main__':
app.run(debug=True)
Run the APP:
Flask includes a built-in HTTP server for testing. Test your API using the following command:
(env) $ python main.py * Serving Flask app "main" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Start the flask server with the help of the given command above. API use get method to retrieve information in the form of JSON or XML format. Check by using running curl URL command:
$ curl http://localhost:5000 { 'Name': { 'fullName': ['Manoj', 'Kumawat'] }, 'Note': { 'message': ['This is my first message.'] } }
How to access API:
import requests
def main():
res = requests.get("http://data.fixer.io/api/latest?access_key=KEY&base=EUR&symbols=USD")
if res.status_code != 200:
raise Exception("ERROR: API requests unsuccessful.")
data = res.json()
rate = data["rates"]["USD"]
print(rate)
if __name__ == '__main__':
main()