{"id":1564,"date":"2019-05-12T14:32:54","date_gmt":"2019-05-12T06:32:54","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1564"},"modified":"2020-05-12T10:47:08","modified_gmt":"2020-05-12T02:47:08","slug":"how-to-create-an-api-endpoint-that-generates-a-qr-code-image-with-python-3-flask-restplus-and-python-qrcode","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-create-an-api-endpoint-that-generates-a-qr-code-image-with-python-3-flask-restplus-and-python-qrcode\/","title":{"rendered":"How to create an API endpoint that generates a QR Code image, with Python 3 Flask-RESTPlus and python-qrcode"},"content":{"rendered":"<p>When you have an API endpoint that generates a QR Code image, another device with a QR Code scanner will be able to get the encoded value to perform some action. For example, WhatsApp web generates a QR Code image that encodes a code for WhatsApp app to sign in the user.<\/p>\n<p>So how can you create an API endpoint that generates a QR Code image? With this in mind, let's look at how we can do so with Python 3 <a href=\"https:\/\/flask-restplus.readthedocs.io\/en\/stable\/\" rel=\"noopener\" target=\"_blank\">Flask-RESTPlus<\/a> and <a href=\"https:\/\/pypi.org\/project\/qrcode\/\" rel=\"noopener\" target=\"_blank\">python-qrcode<\/a>.<\/p>\n<h2>Specifying the Python 3 dependencies for creating an API endpoint that generates a QR Code image<\/h2>\n<p>First, let's proceed with installing the Python 3 dependencies for creating an API endpoint that generates a QR Code image into your Python 3 environment. In order to do so, create a <code>requirements.txt<\/code> file with the following content:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nflask-restplus==0.12.1\r\nPillow==6.0.0\r\nqrcode==6.1\r\n<\/pre>\n<p>As shown above, we will need a href=\"https:\/\/flask-restplus.readthedocs.io\/en\/stable\/\" rel=\"noopener\" target=\"_blank\">flask-restplus<\/a>, <a href=\"https:\/\/pillow.readthedocs.io\/en\/stable\/\">Pillow<\/a> and <a href=\"https:\/\/pypi.org\/project\/qrcode\/\" rel=\"noopener\" target=\"_blank\">qrcode<\/a> for creating an API endpoint that generates a QR Code image.<\/p>\n<h2>Creating the Python 3 code for creating an API endpoint that generates a QR Code image<\/h2>\n<p>In order to keep things simple, let's create the Python 3 codes as a single source file and name it as <code>run_app.py<\/code>:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom flask import Flask, Blueprint, request, send_file\r\nfrom flask_restplus import Api, Namespace, Resource, fields\r\nfrom io import BytesIO\r\n\r\nimport os, qrcode\r\n\r\n# Create Flask app\r\napp = Flask(__name__)\r\n\r\n# Associate Api with Blueprint\r\napi_blueprint = Blueprint('API', __name__)\r\napi = Api(api_blueprint,\r\n    title='Api for QR code app',\r\n    version='1.0',\r\n    description='This is an API for QR code app',\r\n    # All API metadatas\r\n)\r\n\r\n# Create namespace for containing Qr Code related operations\r\nqrcode_namespace = Namespace('QrCode', description='Qr code related operations')\r\n# Specify uri of qrcode namespace as \/qrcode\r\napi.add_namespace(qrcode_namespace, path='\/qrcode')\r\n# Specify uri of api blueprint as \/api\r\napp.register_blueprint(api_blueprint, url_prefix='\/api')\r\n\r\n# Define input model\r\nqrcode_creation_input = qrcode_namespace.model('QRCode creation Input', {\r\n    'value': fields.String(required=True, description='The value that is supposed to be encoded into qrcode'),\r\n})\r\n\r\n\r\n# Define API endpoint for creating Qr Code image\r\n@qrcode_namespace.route('\/')\r\n@qrcode_namespace.doc('Creates a QRCode image based on a string value.')\r\nclass QrCodeRoot(Resource):\r\n\r\n    @qrcode_namespace.expect(qrcode_creation_input)\r\n    @qrcode_namespace.produces(&#x5B;'image\/png'])\r\n    @qrcode_namespace.response(200, description='Return QR Code png image file.')\r\n    @qrcode_namespace.response(400, description='Invalid input provided.')\r\n    def post(self):\r\n\r\n        # Get value to encode into QR Code\r\n        json_input = request.get_json()\r\n        value_to_turn_into_qrcode = json_input&#x5B;'value']\r\n\r\n        # Create qr code image and return it as HTTP response\r\n        pil_img = qrcode.make(value_to_turn_into_qrcode)\r\n        img_io = BytesIO()\r\n        pil_img.save(img_io, 'PNG')\r\n        img_io.seek(0)\r\n        return send_file(img_io, mimetype='image\/png')\r\n\r\n\r\nif __name__ == '__main__':\r\n    port = int(os.getenv(&quot;PORT&quot;, &quot;5678&quot;))\r\n    app.run(host='0.0.0.0', port=port)\r\n<\/pre>\n<h2>Understanding the Python 3 code for creating an API endpoint that generates a QR Code image<\/h2>\n<p>In case you are wondering what the previous Python 3 code does, this section explains the code by parts.<\/p>\n<h3>Importing the necessary dependencies for creating an API endpoint that generates a QR Code image<\/h3>\n<p>First, we import the necessary dependencies for creating an API endpoint that generates a QR code image:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom flask import Flask, Blueprint, request, send_file\r\nfrom flask_restplus import Api, Namespace, Resource, fields\r\nfrom io import BytesIO\r\n\r\nimport os, qrcode\r\n<\/pre>\n<h3>Wiring flask_restplus with Flask to realise the uri for creating an API endpoint that generates a QR Code image<\/h3>\n<p>After we had imported the necessary dependencies, we then proceed to wire Flask Restplus with Flask to realise the url for creating an API endpoint that generates a QR Code image:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Create Flask app\r\napp = Flask(__name__)\r\n\r\n# Associate Api with Blueprint\r\napi_blueprint = Blueprint('API', __name__)\r\napi = Api(api_blueprint,\r\n    title='Api for QR code app',\r\n    version='1.0',\r\n    description='This is an API for QR code app',\r\n    # All API metadatas\r\n)\r\n\r\n# Create namespace for containing Qr Code related operations\r\nqrcode_namespace = Namespace('QrCode', description='Qr code related operations')\r\n# Specify uri of qrcode namespace as \/qrcode\r\napi.add_namespace(qrcode_namespace, path='\/qrcode')\r\n# Specify uri of api blueprint as \/api\r\napp.register_blueprint(api_blueprint, url_prefix='\/api')\r\n<\/pre>\n<p>After the script ran the above codes, we will have a swagger documentation page available via <code>\/api<\/code>. In addition to that, QR Code related API endpoints can be made available via <code>\/api\/qrcode<\/code> through the various decorator functions in <code>qrcode_namespace<\/code>.<\/p>\n<h3>Defining the expected input for the API endpoint that generates a QR Code image<\/h3>\n<p>Next, we then define the input model for the API endpoint that generates a QR Code image:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Define input model\r\nqrcode_creation_input = qrcode_namespace.model('QRCode creation Input', {\r\n    'value': fields.String(required=True, description='The value that is supposed to be encoded into qrcode'),\r\n})\r\n<\/pre>\n<p>Given that, we can then tell Flask RESTPlus to ensure that any <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP request<\/a> made to the API endpoint that generates a QR Code image adheres to the following JSON format:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\n{\r\n  &quot;value&quot;: &quot;string to encode as QR code image&quot;\r\n}\r\n<\/pre>\n<h3>Defining the API endpoint that generates a QR Code image<\/h3>\n<p>Given that we have the input model and namespace, we can then define the API endpoint that generates a QR Code image:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n# Define API endpoint for creating Qr Code image\r\n@qrcode_namespace.route('\/')\r\n@qrcode_namespace.doc('Creates a QRCode image based on a string value.')\r\nclass QrCodeRoot(Resource):\r\n \r\n    @qrcode_namespace.expect(qrcode_creation_input)\r\n    @qrcode_namespace.produces(&#x5B;'image\/png'])\r\n    @qrcode_namespace.response(200, description='Return QR Code png image file.')\r\n    @qrcode_namespace.response(400, description='Invalid input provided.')\r\n    def post(self):\r\n \r\n        # Get value to encode into QR Code\r\n        json_input = request.get_json()\r\n        value_to_turn_into_qrcode = json_input&#x5B;'value']\r\n \r\n        # Create qr code image and return it as HTTP response\r\n        pil_img = qrcode.make(value_to_turn_into_qrcode)\r\n        img_io = BytesIO()\r\n        pil_img.save(img_io, 'PNG')\r\n        img_io.seek(0)\r\n        return send_file(img_io, mimetype='image\/png')\r\n<\/pre>\n<p>In the above code, we defined a HTTP post request handler made to <code>\/api\/qrcode<\/code>. Inside the handler function, we first get the value to encode into QR code image.<\/p>\n<p>After that, we use <code>qrcode.make<\/code> to get a Pillow instance that represents the encoded QR Code image. Given that, we then use an instance of <a href=\"https:\/\/docs.python.org\/3\/library\/io.html#io.BytesIO\" rel=\"noopener\" target=\"_blank\"><code>BytesIO<\/code><\/a> to hold the binary data of that QR Code image.<\/p>\n<p>Once we have done so, we then use the <a href=\"http:\/\/flask.pocoo.org\/docs\/0.12\/api\/#flask.send_file\" rel=\"noopener\" target=\"_blank\">send_file<\/a> function to return the contents of that BytesIO instance as a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-response\/\" rel=\"noopener\" target=\"_blank\">HTTP response<\/a>.<\/p>\n<h3>Running the Flask application with an API endpoint that generates a QR Code image<\/h3>\n<p>At the end of the script, we run the Flask application with the following code:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nif __name__ == '__main__':\r\n    port = int(os.getenv(&quot;PORT&quot;, &quot;5678&quot;))\r\n    app.run(host='0.0.0.0', port=port)\r\n<\/pre>\n<p>The above code first check if the script is being run directly. If that is the case, it then checks if any port is provided as an environment variable named <strong>PORT<\/strong>. If no port is given, the port to run the Flask application is set to <strong>5678<\/strong>.<\/p>\n<p>Given that port number, we then run the Flask application.<\/p>\n<h2>Running example program<\/h2>\n<p>At this point in time, we will have created the following files:<\/p>\n<ul>\n<li>requirements.txt<\/li>\n<li>run_app.py<\/li>\n<\/ul>\n<p>Let's look at how we can run the application.<\/p>\n<h3>Creating a virtual environment to run your Python application<\/h3>\n<p>Since virtual environments help us keep our Python applications in its own isolated environment, let's create one for this application.<\/p>\n<p>Before we begin, let's assume that you are running your Python application in a Linux or Unix environment. <\/p>\n<p>In case you are using Windows, refer to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-create-a-virtual-environment-for-your-python-3-application-with-python3-venv-in-linux-or-unix\/\" rel=\"noopener\" target=\"_blank\">how to create a virtual environment for your Python 3 application in windows<\/a> for more information.<\/p>\n<p>With that in mind, let's run the following command to <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-create-a-virtual-environment-for-your-python-3-application-with-python3-venv-in-linux-or-unix\/\" rel=\"noopener\" target=\"_blank\">create a virtual environment for your Python 3 application with python3-venv in Linux or Unix<\/a> in a shell terminal:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython3 -m venv qrcode-app-env\r\n<\/pre>\n<p>When the command completes, you will have a virtual environment in a directory named <code>qrcode-app-env<\/code>.<\/p>\n<h3>Installing the dependencies to run your Python application<\/h3>\n<p>Once you have created your virtual environment, proceed to activate it:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nsource qrcode-app-env\/bin\/activate\r\n<\/pre>\n<p>When your virtual environment is activated, run the following command to install your Python dependencies:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip install -r requirements.txt\r\n<\/pre>\n<p>After you had installed the Python dependencies, proceed to run your application:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npython run_app.py\r\n<\/pre>\n<h3>Accessing the swagger documentation page for testing your QR code image generation API endpoint<\/h3>\n<p>Once your application is running, you can then use a browser to access <a href=\"http:\/\/requirements.txt\" rel=\"noopener\" target=\"_blank\">http:\/\/localhost:5678\/api<\/a>:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/screenshot-of-API-documentation-page-for-Flask-Restplus-API-endpoint-creating-QR-Code-image.gif\" alt=\"screenshot of API documentation page for Flask Restplus API endpoint creating QR Code image\"\/><\/p>\n<p>Given that, you can then try out the API endpoint in the API documentation page to get a QR Code image:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/screenshot-of-API-documentation-page-with-QR-Code-image-as-response-for-Flask-Restplus-API-endpoint-creating-QR-Code-image-.gif\" alt=\"screenshot of API documentation page with QR Code image as response for Flask Restplus API endpoint creating QR Code image\" \/><\/p>\n<p>When you use a QR Code scanner to scan the QR Code image, you should get the following string value:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nThis is an encoded value for QR Code image\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-pe\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-pe&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-pe&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1564&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When you have an API endpoint that generates a QR Code image, another device with a QR Code scanner will be able to get the encoded value to perform some action. For example, WhatsApp web generates a QR Code image that encodes a code for WhatsApp app to sign in the user.<\/p>\n<p>So how can you create an API endpoint that generates a QR Code image? With this in mind, let&#8217;s look at how we can do so with Python 3 <a href=\"https:\/\/flask-restplus.readthedocs.io\/en\/stable\/\" rel=\"noopener noreferrer\" target=\"_blank\">Flask-RESTPlus<\/a> and <a href=\"https:\/\/pypi.org\/project\/qrcode\/\" rel=\"noopener noreferrer\" target=\"_blank\">python-qrcode<\/a>.<\/p>\n","protected":false},"author":1,"featured_media":1565,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[584,640,226,233,639,641],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/screenshot-of-API-documentation-page-for-Flask-Restplus-API-endpoint-creating-QR-Code-image.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-pe","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1564"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1564"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1564\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1565"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1564"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1564"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1564"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}