(window.webpackJsonp=window.webpackJsonp||[]).push([[27],{466:function(t,a,e){t.exports=e.p+"assets/img/simple-hello-world.e398b85d.png"},467:function(t,a,e){t.exports=e.p+"assets/img/greetings.b6337cba.png"},599:function(t,a,e){"use strict";e.r(a);var s=e(56),n=Object(s.a)({},(function(){var t=this,a=t.$createElement,s=t._self._c||a;return s("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[s("h1",{attrs:{id:"hello-world-with-flask"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#hello-world-with-flask"}},[t._v("#")]),t._v(' "Hello, world!" with Flask')]),t._v(" "),s("h2",{attrs:{id:"why-flask"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#why-flask"}},[t._v("#")]),t._v(" Why Flask?")]),t._v(" "),s("p",[t._v("Flask"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn1",id:"fnref1"}},[t._v("[1]")])]),t._v(" is known as a lightweight WSGI"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn2",id:"fnref2"}},[t._v("[2]")])]),t._v(" application framework. A framework is a code library that makes a developer's life easier while writing application code. Flask helps us build reliable, scalable, and maintainable web applications")]),t._v(" "),s("p",[t._v("Flask lets you quickly get started with building web applications in pure Python. In the following sections, you'll install Flask on your local development machine and make a simple 'Hello, world!' application. Let's jump right in!")]),t._v(" "),s("h2",{attrs:{id:"installing-flask"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#installing-flask"}},[t._v("#")]),t._v(" Installing Flask")]),t._v(" "),s("p",[t._v("Assuming you've got Python 3 installed on your local development machine, let's create a virtual environment"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn3",id:"fnref3"}},[t._v("[3]")])]),t._v(" and install Flask in it. For this demonstration, we'll be using "),s("code",[t._v("Python 3.8")]),t._v(". Run the following commands on your terminal based on your operating system:")]),t._v(" "),s("h3",{attrs:{id:"linux-macos"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#linux-macos"}},[t._v("#")]),t._v(" Linux / MacOS:")]),t._v(" "),s("p",[t._v("Create the virtual environment:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[t._v("python3 -m venv venv\n")])])]),s("p",[t._v("Activate the virtual environment:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[t._v(".")]),t._v(" venv/bin/activate\n")])])]),s("p",[t._v("Install Flask via pip:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[t._v("pip "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("install")]),t._v(" Flask\n")])])]),s("h3",{attrs:{id:"windows"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#windows"}},[t._v("#")]),t._v(" Windows")]),t._v(" "),s("p",[t._v("Create the virtual environment:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[t._v("py -3 -m venv venv\n")])])]),s("p",[t._v("Activate the virtual environment:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[t._v("venv"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("\\")]),t._v("Scripts"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("\\")]),t._v("activate\n")])])]),s("p",[t._v("Install Flask via pip:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[t._v("pip "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("install")]),t._v(" Flask\n")])])]),s("p",[t._v("If you're having trouble with your installation, checkout this detailed installation guide here"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn4",id:"fnref4"}},[t._v("[4]")])]),t._v(".")]),t._v(" "),s("h2",{attrs:{id:"making-a-hello-world-flask-application"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#making-a-hello-world-flask-application"}},[t._v("#")]),t._v(' Making a "Hello, World!" Flask Application')]),t._v(" "),s("p",[t._v("If you go to the Flask"),s("sup",{staticClass:"footnote-ref"},[s("a",{attrs:{href:"#fn5",id:"fnref5"}},[t._v("[5]")])]),t._v(" website, you are welcomed with a very simple example application that has just five lines of code. We'll be building the same application here just to get a hang of how the entire process works.")]),t._v(" "),s("h3",{attrs:{id:"prepare-your-application-directory"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#prepare-your-application-directory"}},[t._v("#")]),t._v(" Prepare Your Application Directory")]),t._v(" "),s("p",[t._v("We'll create a folder called "),s("code",[t._v("hello-world")]),t._v(" and put all our application code inside that. Go to your development directory (where you want to place your code) and run the following command to create the "),s("code",[t._v("hello-world")]),t._v(" folder:")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[s("span",{pre:!0,attrs:{class:"token function"}},[t._v("mkdir")]),t._v(" hello-world\n")])])]),s("h3",{attrs:{id:"write-your-first-hello-world-application"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#write-your-first-hello-world-application"}},[t._v("#")]),t._v(' Write Your First "Hello, World!" Application')]),t._v(" "),s("p",[t._v("Now go to the "),s("code",[t._v("hello-world")]),t._v(" folder that you've just created and create a new Python file called "),s("code",[t._v("app.py")]),t._v(". Add the following lines to the "),s("code",[t._v("app.py")]),t._v(" file.")]),t._v(" "),s("div",{staticClass:"language-python extra-class"},[s("pre",{pre:!0,attrs:{class:"language-python"}},[s("code",[s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("# app.py")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" flask "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Flask\n\napp "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" Flask"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("__name__"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n\n"),s("span",{pre:!0,attrs:{class:"token decorator annotation punctuation"}},[t._v("@app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("route")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"/"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("def")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("hello_world")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Hello, World!"')]),t._v("\n")])])]),s("p",[t._v("Let's see what did the above code do:")]),t._v(" "),s("ul",[s("li",[s("p",[t._v("First we imported the "),s("code",[t._v("Flask")]),t._v(" class.")])]),t._v(" "),s("li",[s("p",[t._v("Then we've create an instance of the class and assigned that to "),s("code",[t._v("app")]),t._v(" variable. This instance of the class will be our WSGI application.")])]),t._v(" "),s("li",[s("p",[t._v("We then use the "),s("code",[t._v("route()")]),t._v(" decorator to tell Flask what URL should trigger our function.")])]),t._v(" "),s("li",[s("p",[t._v("The function is given a unique name and returns the message we want to display in the user’s browser.")])])]),t._v(" "),s("h3",{attrs:{id:"run-the-application"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#run-the-application"}},[t._v("#")]),t._v(" Run the Application")]),t._v(" "),s("p",[t._v("To run the application, you can either use the "),s("code",[t._v("flask")]),t._v(" command or Python’s "),s("code",[t._v("-m")]),t._v(" switch with "),s("code",[t._v("Flask")]),t._v(". Before you can do that you need to tell your terminal the application to work with by exporting the "),s("code",[t._v("FLASK_APP")]),t._v(" environment variable. Also, during development, you should turn on the debugging mode by setting the "),s("code",[t._v("FLASK_ENV")]),t._v(" environment variable to "),s("code",[t._v("development")]),t._v(". Run the following commands if you're on "),s("strong",[t._v("Linux/MacOS")]),t._v(":")]),t._v(" "),s("div",{staticClass:"language-bash extra-class"},[s("pre",{pre:!0,attrs:{class:"language-bash"}},[s("code",[s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[t._v("export")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token assign-left variable"}},[t._v("FLASK_APP")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v("app.py\n"),s("span",{pre:!0,attrs:{class:"token builtin class-name"}},[t._v("export")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token assign-left variable"}},[t._v("FLASK_ENV")]),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v("development\nflask run\n")])])]),s("p",[t._v("Now, if you're on "),s("strong",[t._v("Windows")]),t._v(" then export "),s("code",[t._v("FLASK_APP")]),t._v(" and "),s("code",[t._v("FLASK_ENV")]),t._v(" variables on "),s("em",[t._v("Command Prompt")]),t._v(" like this:")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v("C:\\path\\to\\app>set FLASK_APP=app.py\nC:\\path\\to\\app>set FLASK_ENV=development\n\n")])])]),s("p",[t._v("Or on "),s("em",[t._v("Powershell")]),t._v(", run:")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v('PS C:\\path\\to\\app> $env:FLASK_APP = "app.py"\nPS C:\\path\\to\\app> $env:FLASK_ENV = "development"\n')])])]),s("p",[t._v("Then run:")]),t._v(" "),s("div",{staticClass:"language- extra-class"},[s("pre",{pre:!0,attrs:{class:"language-text"}},[s("code",[t._v("python -m flask run\n")])])]),s("p",[t._v("Now using your browser, head over to "),s("a",{attrs:{href:"http://127.0.0.1:5000/",target:"_blank",rel:"noopener noreferrer"}},[t._v("http://127.0.0.1:5000/"),s("OutboundLink")],1),t._v(", and you should see your 'Hello, world!' greeting.")]),t._v(" "),s("p",[s("img",{attrs:{src:e(466),alt:"simple-hello-world"}})]),t._v(" "),s("p",[t._v("Here, you've created your first API. An Application Programming Interface (API) allows two systems to communicate with one another. Running the Flask application creates a server that allows a client to access the 'Hello, world!' string. Your browser is the client that accesses the server via an API endpoint. The final part of the link "),s("code",[t._v("http://127.0.0.1:5000/")]),t._v(" that you've used to interact with the API is called an endpoint. When the browser accessed the URL, the server runs the "),s("code",[t._v("hello_world()")]),t._v(" function and returns a string that the browser then displays. The "),s("code",[t._v("route()")]),t._v(" decorator takes care of the back and forth communication between the server and the client.")]),t._v(" "),s("h2",{attrs:{id:"serving-an-html-string"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#serving-an-html-string"}},[t._v("#")]),t._v(" Serving an HTML String")]),t._v(" "),s("p",[t._v("Let's make our 'Hello, world!' app a bit more exciting. Here, you'll create a new endpoint and display the 'Hello, world!' greeting in a fancy "),s("code",[t._v("html")]),t._v(" format. Head over to your "),s("code",[t._v("app.py")]),t._v(" file and modify it like the following:")]),t._v(" "),s("div",{staticClass:"language-python extra-class"},[s("pre",{pre:!0,attrs:{class:"language-python"}},[s("code",[s("span",{pre:!0,attrs:{class:"token comment"}},[t._v("# app.py")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("from")]),t._v(" flask "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("import")]),t._v(" Flask\n\n\napp "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" Flask"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),t._v("__name__"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n\n\n"),s("span",{pre:!0,attrs:{class:"token decorator annotation punctuation"}},[t._v("@app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("route")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"/"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("def")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("hello_world")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Hello, World!"')]),t._v("\n\n\n"),s("span",{pre:!0,attrs:{class:"token decorator annotation punctuation"}},[t._v("@app"),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(".")]),t._v("route")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token string"}},[t._v('"/fancy"')]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),t._v("\n"),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("def")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token function"}},[t._v("hello_world_fancy")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("(")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(")")]),s("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(":")]),t._v("\n greetings "),s("span",{pre:!0,attrs:{class:"token operator"}},[t._v("=")]),t._v(" "),s("span",{pre:!0,attrs:{class:"token triple-quoted-string string"}},[t._v('"""\n \n \n\n

Greetings!

\n

Hello, world!

\n\n \n \n """')]),t._v("\n "),s("span",{pre:!0,attrs:{class:"token keyword"}},[t._v("return")]),t._v(" greetings\n")])])]),s("p",[t._v("Notice, how we've introduced another function called "),s("code",[t._v("hello_world_fancy()")]),t._v(" and decorated it like the previously defined "),s("code",[t._v("hello_world()")]),t._v(" function. This time the "),s("code",[t._v("route()")]),t._v(" decorator defines a new endpoint named "),s("code",[t._v("/fancy")]),t._v(". Flask will automatically append this endpoint to your host URL "),s("code",[t._v("http://localhost:5000")]),t._v(". So, the final URL will be "),s("a",{attrs:{href:"http://localhost:5000/fancy",target:"_blank",rel:"noopener noreferrer"}},[t._v("http://localhost:5000/fancy"),s("OutboundLink")],1),t._v(". If you've stopped your server, then run the application again by following the previously mentioned instructions. Then head over to "),s("a",{attrs:{href:"http://localhost:5000/fancy",target:"_blank",rel:"noopener noreferrer"}},[t._v("http://localhost:5000/fancy"),s("OutboundLink")],1),t._v(" on your browser and you'll be greeted by a fancier 'Hello, world!' page.")]),t._v(" "),s("p",[s("img",{attrs:{src:e(467),alt:"greetings-html"}})]),t._v(" "),s("h2",{attrs:{id:"conclusion"}},[s("a",{staticClass:"header-anchor",attrs:{href:"#conclusion"}},[t._v("#")]),t._v(" Conclusion")]),t._v(" "),s("p",[t._v("In this lesson you've learned how to build and serve simple APIs with Flask framework. You've also learned how endpoints work, how to access the server from a client and how to add new routes to your app to send HTML to the browser.")]),t._v(" "),s("hr",{staticClass:"footnotes-sep"}),t._v(" "),s("section",{staticClass:"footnotes"},[s("ol",{staticClass:"footnotes-list"},[s("li",{staticClass:"footnote-item",attrs:{id:"fn1"}},[s("p",[s("a",{attrs:{href:"https://flask.palletsprojects.com/en/1.1.x/",target:"_blank",rel:"noopener noreferrer"}},[t._v("Flask Documentation"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref1"}},[t._v("↩︎")])])]),t._v(" "),s("li",{staticClass:"footnote-item",attrs:{id:"fn2"}},[s("p",[s("a",{attrs:{href:"https://wsgi.readthedocs.io/en/latest/what.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("Getting Started with WSGI"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref2"}},[t._v("↩︎")])])]),t._v(" "),s("li",{staticClass:"footnote-item",attrs:{id:"fn3"}},[s("p",[s("a",{attrs:{href:"https://docs.python.org/3/library/venv.html#:~:text=A%20virtual%20environment%20is%20a,part%20of%20your%20operating%20system.",target:"_blank",rel:"noopener noreferrer"}},[t._v("Python virtual environment"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref3"}},[t._v("↩︎")])])]),t._v(" "),s("li",{staticClass:"footnote-item",attrs:{id:"fn4"}},[s("p",[s("a",{attrs:{href:"https://flask.palletsprojects.com/en/1.1.x/installation/",target:"_blank",rel:"noopener noreferrer"}},[t._v("Installing Flask"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref4"}},[t._v("↩︎")])])]),t._v(" "),s("li",{staticClass:"footnote-item",attrs:{id:"fn5"}},[s("p",[s("a",{attrs:{href:"https://flask.pocoo.org",target:"_blank",rel:"noopener noreferrer"}},[t._v("Flask Website"),s("OutboundLink")],1),t._v(" "),s("a",{staticClass:"footnote-backref",attrs:{href:"#fnref5"}},[t._v("↩︎")])])])])])])}),[],!1,null,null,null);a.default=n.exports}}]);