Building REST APIs With Flask - Edu.anarcho-copy

1y ago
3 Views
2 Downloads
4.51 MB
209 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Axel Lin
Transcription

Building RESTAPIs with FlaskCreate Python Web Serviceswith MySQL—Kunal Relanwww.allitebooks.com

Building REST APIswith FlaskCreate Python Web Serviceswith MySQLKunal Relanwww.allitebooks.com

Building REST APIs with Flask: Create Python Web Services with MySQLKunal RelanNew Delhi, Delhi, IndiaISBN-13 (pbk): 2-5022-8ISBN-13 (electronic): 978-1-4842-5022-8Copyright 2019 by Kunal RelanThis work is subject to copyright. All rights are reserved by the Publisher, whether the whole orpart of the material is concerned, specifically the rights of translation, reprinting, reuse ofillustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,and transmission or information storage and retrieval, electronic adaptation, computer software,or by similar or dissimilar methodology now known or hereafter developed.Trademarked names, logos, and images may appear in this book. Rather than use a trademarksymbol with every occurrence of a trademarked name, logo, or image we use the names, logos,and images only in an editorial fashion and to the benefit of the trademark owner, with nointention of infringement of the trademark.The use in this publication of trade names, trademarks, service marks, and similar terms, even ifthey are not identified as such, is not to be taken as an expression of opinion as to whether or notthey are subject to proprietary rights.While the advice and information in this book are believed to be true and accurate at the date ofpublication, neither the authors nor the editors nor the publisher can accept any legalresponsibility for any errors or omissions that may be made. The publisher makes no warranty,express or implied, with respect to the material contained herein.Managing Director, Apress Media LLC: Welmoed SpahrAcquisitions Editor: Nikhil KarkalDevelopment Editor: Laura BerendsonCoordinating Editor: Divya ModiCover designed by eStudioCalamarCover image designed by Freepik (www.freepik.com)Distributed to the book trade worldwide by Springer Science Business Media New York,233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is aCalifornia LLC and the sole member (owner) is Springer Science Business Media Finance Inc(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/rights-permissions.Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBookversions and licenses are also available for most titles. For more information, reference our Printand eBook Bulk Sales web page at http://www.apress.com/bulk-sales.Any source code or other supplementary material referenced by the author in this book is availableto readers on GitHub via the book’s product page, located at www.apress.com/9781484250211.For more detailed information, please visit http://www.apress.com/source-code.Printed on acid-free paperwww.allitebooks.com

Dedicated to caffeine and sugar, my companionsthrough many long night of writing, andextra credits to my mom.www.allitebooks.com

Table of ContentsAbout the Author ixAbout the Technical Reviewer xiAcknowledgments xiiiIntroduction xvChapter 1: Beginning with Flask 1Introduction to Flask 1Starting Flask 2Flask Components Covered in This Book 3Introduction to RESTful Services 4Uniform Interface 7Representations 8Messages 9Links Between Resources 12Caching 13Stateless 13Planning REST API 14API Design 15Setting Up Development Environment 16Working with PIP 17Choosing the IDE 18Understanding Python Virtual Environments 19vwww.allitebooks.com

Table of ContentsSetting Up Flask 24Installing Flask 25Conclusion 26Chapter 2: Database Modeling in Flask 27Introduction 27SQL Databases 28NoSQL Databases 28Key Differences: MySQL vs. MongoDB 29Creating a Flask Application with SQLAlchemy 30Creating an Author Database 33Sample Flask MongoEngine Application 46Conclusion 58Chapter 3: CRUD Application with Flask (Part 1) 59User Authentication 88Conclusion 96Chapter 4: CRUD Application with Flask (Part 2) 97Introduction 97Email Verification 98File Upload 109API Documentation 114Building Blocks of API Documentation 115OpenAPI Specification 116Conclusion 134vi

Table of ContentsChapter 5: Testing in Flask 135Introduction 135Setting Up Unit Tests 136Unit Testing User Endpoints 139Test Coverage 155Conclusion 157Chapter 6: Deploying Flask Applications 159Deploying Flask with uWSGI and Nginx on Alibaba Cloud ECS 160Deploying Flask on Gunicorn with Apache on Alibaba Cloud ECS 167Deploying Flask on AWS Elastic Beanstalk 172Deploying Flask App on Heroku 176Adding a Procfile 177Deploying Flask App on Google App Engine 180Conclusion 182Chapter 7: Monitoring Flask Applications 183Application Monitoring 183Sentry 185Flask Monitoring Dashboard 187New Relic 189Bonus Services 192Conclusion 194Index 195vii

About the AuthorKunal Relan is an iOS security researcherand a full stack developer with more thanfour years of experience in various fieldsof technology, including network security,DevOps, cloud infrastructure, and applicationdevelopment, working as a consultant withstart-ups around the globe. He is an AlibabaCloud MVP and author of iOS PenetrationTesting (Apress) and a variety of white papers.Kunal is a technology enthusiast and an activespeaker. He regularly contributes to open source communities and writesarticles for Digital Ocean and Alibaba Techshare.ix

About the Technical ReviewerSaurabh Badhwar is a software engineerwith a passion to build scalable distributedsystems. He is mostly working to solvechallenges related to performance of softwareat a large scale and has been involved inbuilding solutions that help other developersquickly analyze and compare performanceof their systems when running at scale.He is also passionate about working withopen source communities and has beenactively participating as a contributor in various domains, which involvedevelopment, testing, and community engagement. Saurabh has also beenan active speaker at various conferences where he has been talking aboutperformance of large-scale systems.xi

AcknowledgmentsI would like to thank Apress for providing me this platform, without whichthis would have been a lot harder. I would also like to thank Mr. NikhilKarkal for his help and Miss Divya Modi for her perseverance, withoutwhom this would have been a farsighted project.I’d like to mention about the strong Python community which helpedme understand the core concepts in my early years of programming, whichinspired me to contribute back to the community with this book.Last but certainly not the least, I would like to acknowledge all thepeople who constantly reminded me about the deadlines and helped mewrite this book, especially my family and Aparna Abhijit for helping me outwith editing.xiii

IntroductionFlask is a lightweight microframework for web applications built on topof Python, which provides an efficient framework for building web-basedapplications using the flexibility of Python and strong community supportwith the capability of scaling to serve millions of users.Flask has excellent community support, documentation, andsupporting libraries; it was developed to provide a barebone framework fordevelopers, giving them the freedom to build their applications using theirpreferred set of libraries and tools.This book takes you through different stages of a REST API–basedapplication development process using flask which explains the basics ofthe Flask framework assuming the readers understand Python. We’ll coverdatabase integration, understanding REST services, REST APIs performingCRUD operations, user authentication, third-party library integrations,testing, deployment, and application monitoring.At the end of this book, you’ll have a fair understanding of Flaskframework, REST, testing, deploying, and managing Flask applications,which will open doors to understanding REST API development.xv

CHAPTER 1Beginning with FlaskFlask is a BSD licensed, Python microframework based on Werkzeug andJinja2. Being a microframework doesn’t make it any less functional; Flaskis a very simple yet highly extensible framework. This gives developersthe power to choose the configuration they want, thereby making writingapplications or plugins easy. Flask was originally created by Pocoo, ateam of open source developers in 2010, and it is now developed andmaintained by The Pallets Project who power all the components behindFlask. Flask is supported by an active and helpful developer communityincluding an active IRC channel and a mailing list.I ntroduction to FlaskFlask has two major components, Werkzeug and Jinja2. While Werkzeugis responsible for providing routing, debugging, and Web Server GatewayInterface (WSGI), Flask leverages Jinja2 as template engine. Natively,Flask doesn’t support database access, user authentication, or any otherhigh-level utility, but it does provide support for extensions integration toadd all such functionalities, making Flask a micro- yet production-readyframework for developing web applications and services. A simple Flaskapplication can fit into a single Python file or it can be modularized tocreate a production-ready application. The idea behind Flask is to build agood foundation for all applications leaving everything else on extensions. Kunal Relan 2019K. Relan, Building REST APIs with Flask, https://doi.org/10.1007/978-1-4842-5022-8 11

Chapter 1Beginning with FlaskFlask community is quite big and active with hundreds of open sourceextensions. The Flask core team continuously reviews extensions andensures approved extensions are compatible with the future releases. Flaskbeing a microframework provides flexibility to the developers to choosethe design decisions appropriate to their project. It maintains a registry ofextensions which is regularly updated and continuously maintained. Starting FlaskFlask, just like all other Python libraries, is installable from the PythonPackage Index (PPI) and is really easy to setup and start developing with,and it only takes a few minutes to getting started with Flask. To be able tofollow this book, you should be familiar with Python, command line (or atleast PIP), and MySQL.As promised, Flask is really easy to start with, and just five lines of codelets you get started with a minimal Flask application.Listing 1-1. Basic Flask Applicationfrom flask import Flaskapp Flask( name )@app.route('/')def hello world():return 'Hello, From Flask!'if name ' main ':app.run()The preceding code imports the Flask library, initiates the applicationby creating an instance of the Flask class, declares the route, and thendefines the function to execute when the route is called. This code isenough to start your first Flask application.2

Chapter 1Beginning with FlaskThe following code launches a very simple built-in server, whichis good enough for testing but probably not when you want to go inproduction, but we will cover that in the later chapters.When this application starts, the index route upon request shall return“Hello From Flask!” as shown in Figure 1-1.Figure 1-1. Flask minimal application Flask Components Covered in This BookNow that you have been introduced to Flask, we will discuss thecomponents that we’ll cover in Flask REST API development in this book.This book will serve as a practical guide to REST API developmentusing Flask, and we’ll be using MySQL as the backend database. As alreadydiscussed, Flask doesn’t come with native database access support, andto bridge that gap, we’ll use a Flask extension called Flask-SQLAlchemywhich adds support for SQLAlchemy in Flask. SQLAlchemy is essentially3

Chapter 1Beginning with Flaska Python SQL toolkit and Object Relational Mapper which provides thedevelopers the full power and flexibility of SQL.SQLAlchemy provides full support for enterprise-level design patternsand is designed for high-performing database access while maintainingefficiency and ease of use. We’ll build a user authentication module, CRUD(Create, Read, Update, and Delete) REST APIs for object creation, retrieval,manipulation, and deletion. We’ll also integrate a documentation utilitycalled Swagger for creating API documentation, write unit and integrationtests, learn application debugging, and, finally, check out differentmethods of deploying and monitoring our REST APIs on cloud platformsfor production use.For unit tests, we’ll use pytest which is a full-featured Python testingtool—pytest is easy to write tests with and yet is scalable to supportcomplex use cases. We’ll also use Postman which is a complete REST APIPlatform—Postman provides integration tools for every stage of the APIlifecycle, making API development easier and more reliable.API deployment and monitoring are critical parts of REST APIdevelopment; development paradigm changes drastically when it comesto scaling the APIs for production use cases, and for the sake of this book,we’ll deploy our REST APIs using uWSGI and Nginx on a cloud Ubuntuserver. We’ll also deploy our REST APIs on Heroku which is a cloudplatform that facilitates Flask app deployment and scaling out of the box.Last but not least, we’ll discuss debugging common Flask errors andwarnings and debugging Nginx requests and check out Flask applicationmonitoring ensuring least amount on the downtime for production use. Introduction to RESTful ServicesRepresentational State Transfer (REST) is a software architectural stylefor web services that provides a standard for data communicationbetween different kinds of systems. Web services are open standard4

Chapter 1Beginning with Flaskweb applications that interact with other applications with a motive ofexchanging data making it an essential part of client server architecture inmodern web and mobile applications. In simple terms, REST is a standardfor exchanging data over the Web for the sake of interoperability betweencomputer systems. Web services which conform to the REST architecturalstyle are called RESTful web services which allow requesting systems toaccess and manipulate the data using a uniform and predefined set ofstateless operations.Since its inception in 2000 by Roy Feilding, RESTful architecture hasgrown a lot and has been implemented in millions of systems since then.REST has now become one of the most important technologies for web- based applications and is likely to grow even more with its integrationin mobile and IoT-based applications as well. Every major developmentlanguage has frameworks for building REST web services. REST principlesare what makes it popular and heavily used. REST is stateless, making itstraightforward for any kind of system to use and also making it possiblefor each request to be served by a different system.REST enables us to distinguish between the client and the server,letting us implement the client and the server independently. The mostimportant feature of REST is its statelessness, which simply means thatneither the client nor the server has to know the state of each other tobe able to communicate. In this way, both the client and the server canunderstand any message received without seeing the previous message.Since we are talking about RESTful web services, let’s take a dive into webservices and compare other web service standards.Web services in a simple definition is a service offered by oneelectronic device to another, enabling the communication via the WorldWide Web. In practice, web services provide resource-oriented, web- based interface to a database server and so on utilized by another webclient. Web services provide a platform for different kinds of systems tocommunicate to each other, using a solution for programs to be able tocommunicate with each other in a language they understand (Figure 1-2).5

Chapter 1Beginning with FlaskFigure 1-2. REST architecture diagramSOAP (Simple Object Access Protocol) is another web servicecommunication protocol which has been overtaken by REST in therecent years. REST services now dominate the industry representingmore than 70% of public APIs according to Stormpath. They operate byexposing consistent interface to access named resources. SOAP, however,exposes components of application logic as services rather than data.SOAP is now a legacy protocol originally created by Microsoft and has alot of other constraints when compared to REST. SOAP only exchangesdata over XML, and REST provides the ability to exchange data over avariety of data formats. RESTful services are comparatively faster and lessresource intensive. However, SOAP still has its own use cases in which it’s apreferred protocol over REST.SOAP is preferred when robust security is essential as it providessupport for Web Services Security (WS-Security), which is a specificationdefining how security measures are implemented in web services toprotect them from external attacks. Another advantage of SOAP over RESTis its built-in retry logic to compensate for failed requests unlike REST inwhich the client has to handle failed requests by retrying. SOAP is highlyextensible with other technologies and protocols like WS-Security,WS- addressing, WS-coordination, and so on which provides it an edgeover other web service protocols.6

Chapter 1Beginning with FlaskNow, when we have briefly discussed web services—REST and SOAP—let’s discuss features of REST protocol. In general, REST services aredefined and implemented using the following features:1. Uniform interface2. Representations3. Messages4. Links between resources5. Caching6. StatelessU niform InterfaceRESTful services should have a uniform interface to access resources, andas the name suggests, APIs’ interface for the system should be uniformacross the system. A logical URI system with uniform ways to fetch andmanipulate data is what makes REST easy to work with. HTTP/1.1 providesa set of methods to work on noun-based resources; the methods aregenerally called verbs for this purpose.In REST architecture, there is a concept of safe and idempotentmethods. Safe methods are the ones that do not modify resources like a GETor a HEAD method. An idempotent method is a method which producesthe same result no matter how many times it is executed. Table 1- 1 providesa list of commonly used HTTP verbs in RESTful services.7

Chapter 1Beginning with FlaskTable 1-1. Commonly used HTTP verbs useful in RESTful servicesVerbCRUDOperationSafe IdempotentGETReadFetch a single or multiple resourceYesYesPOSTCreatedInsert a new resourceNoNoPUTUpdate/CreateInsert a new resource or updateexistingNoYesDELETEDeleteDelete a single or multiple resourceNoYesOPTIONS READList allowed operations on a resourceYesYesHEADREADReturn only response headers and nobodyYesYesPATCHUpdate/ModifyOnly update the provided changes tothe resourceNoNo RepresentationsRESTful services focus on resources and providing access to the resources.A resource can be easily thought of as an object in OOP. The first thing todo while designing RESTful services is identifying different resources anddetermining the relation between them. A representation is a machine- readable explanation defining the current state of a resource.Once the resources are identified, representations are the next courseof action. REST provides us the ability to use any format for representingthe resources in the system. Unlike SOAP which restricts us to use XML torepresent the data, we can either use JSON or XML. Usually, JSON is thepreferred method for representing the resources to be called by mobile orweb clients, but XML can be used to represent more complex resources.Here is a small example of representing resources in both formats.8

Chapter 1Beginning with FlaskListing 1-2. XML Representation of a Book Resource ?xml version "1.0" encoding "UTF-8"? Book ID 1 /ID Name Building REST APIs with Flask /Name Author Kunal Relan /Author Publisher Apress / Publisher /Book Listing 1-3. JSON Representation of a Book resource{"ID": "1","Name": "Building REST APIs wiith Flask","Author": "Kunal Relan","Publisher": "Apress"}In REST Systems, you can use either of the methods or both themethods depending on the requesting client to represent the data.M essagesIn REST architecture, which essentially established client–server styleway of data communication, messages are an important key. The clientand the server talk to each other via messages in which the client sendsa message to the server which is often called as a request and the serversends a response. Apart from the actual data exchanged between theclient and the server in the form of request and response body, there issome metadata exchanged by the client and the server both in the formof request and response headers. HTTP 1.1 defines request and responseheaders formats in the following way in order to achieve a uniform way ofdata communication across different kinds of systems (Figure 1-3).9

Chapter 1Beginning with FlaskFigure 1-3. HTTP sample requestIn Figure 1-4, GET is the request method, “/comments” is the path inthe server, “postId 1” is a request parameter, “HTTP/1.1” is the protocolversion that the client is requesting, “jsonplaceholder.typicode.com” is theserver host, and content type is a part of the request headers. All of thesecombined is what makes a HTTP request that the server understands.In return, the HTTP server sends the response for the requestedresources.[{"postId": 1,"id": 1,"name": "id labore ex et quam laborum","email": "Eliseo@gardner.biz","body": "laudantium enim quasi est quidem magnam voluptateipsam eos\ntempora quo necessitatibus\ndolor quamautem quasi\nreiciendis et nam sapiente accusantium"},{"postId": 1,"id": 2,"name": "quo vero reiciendis velit similique earum","email": "Jayne Kuhic@sydney.com",10

Chapter 1Beginning with Flask"body": " est natus enim nihil est dolore omnis voluptatemnumquam\net omnis occaecati quod ullam at\nvoluptatemerror expedita pariatur\nnihil sint nostrum voluptatemreiciendis et"},{"postId": 1,"id": 3,"name": "odio adipisci rerum aut animi","email": "Nikita@garfield.biz","body": "quia molestiae reprehenderit quasi aspernatur\nautexpedita occaecati aliquam eveniet laudantium\nomnisquibusdam delectus saepe quia accusamus maiores namest\ncum et ducimus et vero voluptates excepturideleniti ratione"},{"postId": 1,"id": 4,"name": "alias odio sit","email": "Lew@alysha.tv","body": "non et atque\noccaecati deserunt quas accusantiumunde odit nobis qui voluptatem\nquia voluptasconsequuntur itaque dolor\net qui rerum deleniti utoccaecati"},{"postId": 1,"id": 5,"name": "vero eaque aliquid doloribus et culpa","email": "Hayden@althea.biz",11

Chapter 1Beginning with Flask"body": " harum non quasi et ratione\ntempore iure exvoluptates in ratione\nharum architecto fugitinventore cupiditate\nvoluptates magni quo et"}]Figure 1-4. HTTP sample responseIn the preceding figure, “HTTP/2” is the response HTTP version and“200” is the response code. The part below that till “cf-ray” is the responseheaders, and the array of post comments below “cf-ray” is the responsebody of the request. Links Between ResourcesA resource is the fundamental concept in the world of REST architecture.A resource is an object with a type, associated data, and relationships toother resources alongside a set of methods that can be executed on it.The resource in a REST API can contain link to other resources whichshould drive the process flow. Such as in the case of a HTML web page in12

Chapter 1Beginning with Flaskwhich the links in the homepage drive the user flow, resources in REST APIshould be able to drive the flow without the user knowing the process map.Listing 1-4. A Book with Link to Buy{"ID": "1","Name": "Building REST APIs wiith Flask","Author": "Kunal Relan","Publisher": "Apress","URI" : "https://apress.com/us/book/123456789"} CachingCaching is a technique that stores a copy of a given resource and serves itback when requested, saving extra DB calls and processing time. It can bedone at different levels like the client, the server, or a middleware proxyserver. Caching is an important tool for increasing the API performanceand scaling the application; however, if not managed properly, it resultsin the client being served old results. Caching in REST APIs is controlledusing HTTP headers. Cache headers have been an essential part of HTTPheader specifications and have been an important part of scaling webservices with efficiency. In RE

Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science Business Media Finance Inc . MySQL vs MongoDB 29 . This book will serve as a practical guide to REST API development using Flask, and we'll .

Related Documents:

structures. RPGLE source members are not provided for all APIs, most notably the UNIX-Type APIs. Types of APIs There are three general types of available APIs: Original Program Model (OPM) Integrated Language Environment (ILE) UNIX-Type You can call all three types of APIs from an ILE program, but you can only call OPM APIs from an OPM program.

9. Place the acid solution in the Erlenmeyer flask under the buret filled with base. Begin the titration by slowly adding 1 mL base from the buret to the acid solution in the Erlenmeyer flask. Swirl the Erlenmeyer flask after you add the base so the chemicals are well-mixed. Continue to add 1 mL portions of base to the flask, swirling after .

condensing column and drops of distillate collect in the Erlenmeyer flask. 9. When the volume in the boiling flask is reduced to half the original volume, turn off the heating mantle and allow the apparatus to cool. 10. When the system is cool, remove the distillate flask and demonstrate that the flask contains pure alcohol. Distillation of .

rubber seal. If low, carefully pour more CryoCool into the chamber while holding down the flask. Immediately wipe clean any CryoCool that spills onto the rubber seal. Fit the white insulating Flask Seal over the glass flask to secure the flask in the chamber

Note 1: Use 500 ml 0.2 Pm low protein binding filter flask to sterilize medium once all components have been added. Test an aliquot in incubator to ensure that medium is sterile. . (25 ml MEF medium) 2. Grow each flask to extreme confluency and then trypsinize and split each flask 1:5. 3. Repeat step 2 for each flask splitting 1:5 each time .

Building APIs with Django and Django Rest Framework starts where theDjango “Polls” tutorialstops, and takes you through building the polls app, but this time using APIs. You will learn the basics of Django Rest Framework including serialization, views, generic views, viewsets, testing, ac

consume REST APIs, and those who implement REST services. Every server-side programming language offers a variety of open-source and commercial frameworks to implement REST services. Similarly on the client-side, because REST is a thin layer on top of the HTTP protocol, every SDK, whether native or web, can consume REST APIs out of the box.

Agile software development refers to a group of software development methodologies based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams. The term was coined in 2001 when the Agile Manifesto was formulated. Different types of agile management methodologies can be employed such as Extreme Programming, Feature .