Merken

Building beautiful RESTful APIs using Flask

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
the 1 in this in this we now have me how was when I taught us of all the building beautiful and RESTful API system lots this development was called to be thank hi everyone thank you for coming to my
talk um I'm going to say a few words about myself 1st linens me how I write a blog which you you're welcome to visit and I do a little bit of everything I do a little bit of Linux administration I couldn't Python and and JavaScript and I'm currently working at Intel as a technique for would you like to so before I begin that the actual subject of of my presentation I want to get the ball review of the of how many of you know what restaurants already OK that's nearly every how many of you know what's libraries of a few I I meant to give a few introductory slides for everybody who didn't raise their hands and let's begin with the definition of what an API when we're building a model of applications that they usually have a component running in the browser it's interactivity powered by JavaScript we may have a client on the mobile space on the phone and tablet and the 1st we have our server with all the data in the database and in order to get these things to talk to 1 another we need a way for them to communicate which is the API and what is the rest of for rest and Representational State Transfer which sounds complicated but in reality it's
just a clever way to use HTTP to build so in order to talk about rest we need to talk about http at least a little bit so the basics are like everybody knows the the client sends a request to the server sends back a response that both request and the response can be further subdivided into these parts this method
it is things like gets were host they decide what will happen when the server gets the request of get traditionally was to fetch the resources from the from the server post was used to submit data in the form but there are quite a few other methods that can also be used in the past traditionally was a path to a file on a server these days it's actually in in the case of RESTful API it shows us which end point we're going to use in there and then there's also the query which goes into the same aligned with the past and there we can specify parameters then we have had areas which is to is to place we work through which we send copies back and forth and then there's the body of the request which in case of the Esquipulas will be talking about is going to contain Jason responses simpler slightly only has 1 field in the top row which is the status code that comes back with 200 if everything is OK you know and it may come back with an error message like for for 500 but there's a long list of other status goes that the status codes that are defined in HDP and these can also be used so rest is a conventional which we can through which we can use a stick being to access methods of or EPI these are usually divided into collections items and a special entity called the control so the collection and the item and point like in the example for the collection is just books it allows us to and fetch a list of books from our API by issuing a GET request to that end point or to create a new book by issuing a POST request to that end point with information about the new book that we want to create an item that has an and point with 90 so in our case FlashBox slash 23 8 1 2 3 identifies a specific book and this allows us to perform operations on a particular book so it will issue a GET request will get the information of the book if we the use of a book request we can update about or deleted when the delete request so these are all crowd to create up the previous delete operations but oftentimes we need to issue other more specific instructions to our API and for that we can use the controller which can have an address like in this particular case book ID borrow and this allows us to for for example borrow book from the library so that's all the introduction that out of the way and we can move on to talking about some some Python library slides I'm going to be showing the code samples and going to be showing you I are all based on flask and flask is a where micro-framework framework how many of you know flask great OK so so flask is that is the microphone the micro framework so that in itself is not very opinionated and doesn't do very much for you but it has this whole ecosystem of extensions that you can use with it and to the real hero of the story is this extension to class class cost plus and then it handles a lot of the
common in common tasks we have to do to define an API for us and it validates input and gives us service that there's anything wrong with our input it conformant part of so we can return 4 of from argue method we can return something like SQL welcoming objects and that will be automatically transformed into adjacent objects according to a specification that would provide it can in a even turn Python exceptions into HTTP responses so we don't need to worry that will raise an exception somewhere that it's going to return the 500 we can catch it and turn it into a very specific error message like 4 0 4 and 5 which were looking for and then it doesn't matter where code the exceptions that raised it will be intercepted by DAPI and turn it into a machine readable an error message and last the response is pretty cool because it allows us to use very minimal boilerplate code but it cannot killer feature is actually the fact that it generates swagger for us so that did do generates interactive documentation for so with that will come to the part of the presentation that can go wrong so I wonder if we're going to have a
little demo it's going to be really minimal so of the book that I have a local copy of the sort of this set of running here on my computer so I'm just going to to go to
the URL of the character and what we get is a list of all the methods that I defined in In the API so this is just a sample for some some blog categories posts and we can look at the list of methods that we have and that we can actually use them so we get an entry for post method we provided with a properly formatted Jason object that can create a blog posts we conclude tried out and it will actually submit their requests to the API and it will give us all the information about what happens is the response coded in my case tool 1 and there's an explanation appeared to 201 1 means post successfully created of medical so there is also the the body of the response with the lady of the newly created post and any other information that you would wish to provide then I can go through uh to another point that can attach a particular uh idea particular posts from the API i so that the idea was can go to try it out and I get my newly created post back so very simple way to navigate your API to learn the methods that has can browse through the documentation because and if you put documentation in here it will be and the this is the part of the general that goes wrong you can find any documentation and I think in so hard and you can actually thought that uh the documentation here that will be a formative with market and displayed for the user so this is great for other developers that want to consume your API and
and you get this automatically just by using the class compressed plasterers class so this is how does this work this this works because this was generation that because class Chris was generated and and a specification of the API in open API format if it's more or less what it looks like it's just a list of all the definitions of your methods and the inputs and outputs of these methods and this is pretty cool because this open API specification is standard error is becoming a standard now and so there's tooling that's growing around this this format so every is just 1 of the tools that we just saw but there's also something called the swagger editor that allows us to edit the that specification and they're also called generators so if you have a swagger documentation for your API you can run through a code generator and generate clients for your API in different languages so this is so this initiative has many powerful members of these companies are as supporting it to an open source product so I think it's the it's going great but now let's go to the to exactly how we can use last pressed plus 2 to get all this done so I will start with the request fields and the first one on the list there is the request method so in order to get an API using phosphorus was going to do is define a class which inherits from something called called the resource and the library and then in that function in the class we define functions which match by name the different operations that HTTP
that provides so we can define a get with the the poster for the solid and the and that's it that's all we really have to do and you'll notice that in documentation I put in this method and that automatically becomes the documentation that is displayed and the swagger you wife if you have a list of methods methods they become nice interactive list in and the swagger and the work of the next part is the request pass in the actual URL path to the end point and you define that just by adding them and the API route decorated to your class and you can specify parameters which will be part of the past just like putting things in angle brackets in the in the past definition so after the colon there is is the name of the parameters before you can define the types so that will also be validated by your API that will check if it's if it's the right type it's not return a 404 saying that you couldn't find that particular path all these become part of the Interactive and swagger documentation again next this the query and query is the composed of fields so to get and a query into your API method and then check if it's valid to use something called a request part so you create a request a object and then you add fields to this to to the definition because that's where the name of each field type even additional options like will like if it's required or not or options that uses that that are valid and all this will get automatically validated when the request comes to attach this to attach your request passes to enough method you just use this API expect decorator and then you can also use the deposits when the body of your method to get the actual values of the of the arguments if they're about and this of course also becomes part of the interactive forms of options right next thing this what is the body of the request that comes in and fast response to validate whether their requests properly formatted whether the body of the crests properly formatted uses something called an API model so this is slightly similar to the request partially also add fields to a definition and a but it's more it's more flexible and that's how the basic example looks like we'll use they can expect that created to attach it to a method and then in this 1 very light you get that payload text field that comes with additional documentation on on the right you see what they expected format it's and these API models are actually quite a bit more flexible because of 2 things there's they allow inheritance and nesting so both of these are on this slide you see that 1st and defining a model called category and then a model called category with posts because I'm using the API inherit methods that category with posts model will inherit everything every field from categories of automatically it will include all the fields from the from the model that specifies that the end of the line and it will also include these additional fields that I'm providing it In the inheritance and the field I'm actually extending this model is called post here is a nested field which is actually a list of nested blog posts because it's actually quite easy to read a list of the books so this model will expect to get um as an object which contains a list of other objects in the this works very well for more complex cases then we can go on to the response in the field of the response object that status can be documented uh by just adding an API Response decorated to either the resource class differences for the different applies to every endpoint him in your entire resources or to specific methods and then that's enough to get that imitation and at the end you see there good what to return a particular and status code from the API all we need to do is to return a 2nd and 2nd value from the method and that's a fast convention that if number it was just the actual HTTP status code so that's what a table of the document and responses looks like and the last on our list the last part of the response that I'm going to talk about is the body and use the same API models to format your output of your of world you're behind them so you can actually use them both for validating input and formatting output this when you're actually outputting something from your API you may point to a different attribute on your on your objects then the 1 that you want to have in the output so like in this example I have category underscore B which is just an images but it comes from and and object within which is linked to my so as to lock in the object that is that the has a relation to my blog posts of category that says if you recall maybe we can actually use the whole the strength of fields connected by periods show the path to get there and it's it's more complicated than that we can only user-callable too quickly to calculate the value of the of the field that we will up to this fella API that we want to use this model for formatting the output we use the Marshall with decorator where we're planning to return a whole list of items from are from our API and we can use the Marshall list with victory in that's all you going to automate the output it's pretty OK so this last but not least and we can tell the API to handle exceptions for us this is how this is how this can be done you can use the API there the decorator on a method to specify this will be your error handler for this particular type of so like I mentioned before if we if we use this error handler then wherever in our code we get no results found exception wherever that is raised that will be caught before the the API returns and in this case it will longer warning and then return a 404 message if we don't catch an error and were running in the bottom of locally then we get something that's also pretty cool and interactive debugger which runs in the browser and this is part of last this part the but if think comes from work so anyway so you get this you get this interactive debugger which runs in your browser and you can write code Python code in here and see what's what's going on without ever leaving of ever leaving the browser if you want to so this was my rundown of for all the features that last restless provides so now how much would you pay is all you need is 10 lines of code to get started with this this is like a minimal Hello world the API that will come with all the features that that there's a more complete than the code them all and an article about all this on my blog so if you if you go there you you can download the demo I showed you and read a little bit more about the things said thank you thank you we have we have time for questions 1st I think things will go a do you have any feedback about Evie's another fast library for forest baby I stand in the noise you can use some way of discovering to the need the rest of the class that to avoid writing the ideas the views of the modern times 1 and of our data and ones in the is still alchemy OK this is well so I guess the the 2 questions each and we we've tried using these and it's actually very cool because it automatically generates the whole API and and RESTful API for for you based on your uh based on your model definitions but for reading in the end decided that we don't want to expose the database as is the authority I would we actually need custom and points so that's why you we did and of using that and now I don't have any way to create an API from SQL and definitions but it should be straightforward thing to do so I guess it could be attempted but I haven't found something that President thanks you said that a major can be generated from the open API definition file containing that be done with for flask the rest of us not yet and so then the code generator which is part of the and open API the initiative comes with them it's essentially a set of templates for different languages and there is 1 for fast but it uses a different a different library not last response so I was actually thinking of of doing the generating a set of templates for for disco generated but I couldn't find the time to do it myself yet so maybe somebody will do it and then it will be possible I have things for a very good presentation and I was just wondering about your experiences with the workflow the direction of the workflow because if I understand correctly the authority of the structure is the flask applications due to by virtue of its decorators and that generates then the API um In our experience we usually have a different direction like we design we designed the API together with the front-end developers and foreign donors and that becomes sort of the authority the canonical but this of the animal From swagger API is the canonical definition of what we need to do and so then write the back end to conform to that and the front and people then obviously right their clients so that so that has like in the reverse direction of how was your experience with with with what you described below that the truth is I don't have experience doing it that way I I wish I did it sounds like the right way to do it should that in our case we were creating the API by writing code and then the specification came out of that means that the other way around and but then I have a question for you so how can we what happens when you change the uh definition you regenerate the code we don't generate any code you you know we crafted lovingly by hand that is our enough set of our such a selling point um downwards instances is correctly when it does change and it which 1st change the animal and then we discuss whether that makes sense and then maybe we start going through in practice it's it's optional I don't care about actually write something that because there is no no there's a good reason for it and then you have to to keep them in sync yet I find that distances last lesser of 2 evils program and the 1 has to question of does they thank you and this false grasp must provide anything for a hyper to related resources and not out of the box that we have had to implement our own logic the time with the 2 of them later Texas begin again
Metropolitan area network
REST <Informatik>
Gebäude <Mathematik>
Physikalisches System
Softwareentwickler
Baum <Mathematik>
Server
Bit
Web log
Browser
Interaktives Fernsehen
Kartesische Koordinaten
Aggregatzustand
Kombinatorische Gruppentheorie
Raum-Zeit
Computeranimation
W3C-Standard
Client
Informationsmodellierung
Code
Wärmeübergang
Endogene Variable
Programmbibliothek
Zusammenhängender Graph
MIDI <Musikelektronik>
Datenhaltung
REST <Informatik>
Singularität <Mathematik>
Gebäude <Mathematik>
Systemverwaltung
Endogene Variable
REST <Informatik>
Rechenschieber
Tablet PC
Mereologie
Server
Wort <Informatik>
Ordnung <Mathematik>
Baum <Mathematik>
Punkt
Computeranimation
Interaktives Fernsehen
Code
Gamecontroller
Umwandlungsenthalpie
Parametersystem
Nichtlinearer Operator
Managementinformationssystem
Extremwert
REST <Informatik>
Abfrage
Ausnahmebehandlung
Ein-Ausgabe
Dateiformat
Datenfeld
Garbentheorie
Funktion <Mathematik>
Ein-Ausgabe
Server
Information
Fehlermeldung
Klasse <Mathematik>
Kombinatorische Gruppentheorie
Framework <Informatik>
Code
Datensichtgerät
Task
W3C-Standard
Virtuelle Maschine
Bildschirmmaske
Datensatz
Mailing-Liste
Task
Stichprobenumfang
Endogene Variable
Programmbibliothek
Maßerweiterung
Tropfen
Transinformation
Cookie <Internet>
Mailing-Liste
Elektronische Publikation
Endogene Variable
REST <Informatik>
Objekt <Kategorie>
Flächeninhalt
Mereologie
Gamecontroller
Textbaustein
Demo <Programm>
Punkt
Web log
Kategorie <Mathematik>
Mailing-Liste
Computer
Quick-Sort
Computeranimation
Objekt <Kategorie>
Metropolitan area network
Menge
Stichprobenumfang
Endogene Variable
Mereologie
Information
Softwareentwickler
Gammafunktion
Offene Menge
Demo <Programm>
Browser
Schreiben <Datenverarbeitung>
Computeranimation
Richtung
Client
Poisson-Klammer
Standardabweichung
Code
Gerade
Expertensystem
Differenzenrechnung
Sichtenkonzept
Kategorie <Mathematik>
Winkel
REST <Informatik>
Wurm <Informatik>
Ausnahmebehandlung
Biprodukt
Web log
Generator <Informatik>
Menge
Rechter Winkel
Ordnung <Mathematik>
Fehlermeldung
Instantiierung
Tabelle <Informatik>
Subtraktion
Klasse <Mathematik>
Mathematisierung
Automatische Handlungsplanung
Geräusch
Mathematische Logik
Stichprobenfehler
Homepage
Informationsmodellierung
Bildschirmmaske
Endogene Variable
Datentyp
Programmbibliothek
Vererbungshierarchie
Abstand
Generator <Informatik>
Datenstruktur
Attributierte Grammatik
Formale Grammatik
Open Source
Datenmodell
Elektronische Publikation
Zeichenkette
Offene Menge
Debugging
Baum <Mathematik>
Resultante
Bit
Punkt
Web log
Texteditor
Formale Sprache
Kartesische Koordinaten
Synchronisierung
Eins
Metropolitan area network
Minimum
Lambda-Kalkül
Funktion <Mathematik>
Umwandlungsenthalpie
Lineares Funktional
Parametersystem
Datenhaltung
Template
Abfrage
Ein-Ausgabe
Frequenz
Dateiformat
Konfiguration <Informatik>
Rechenschieber
Texteditor
Datenfeld
Dateiformat
URL
Reelle Zahl
Message-Passing
Standardabweichung
Rückkopplung
Quader
Interaktives Fernsehen
Zahlenbereich
Kombinatorische Gruppentheorie
Code
Message-Passing
Task
Front-End <Software>
Softwareentwickler
Optimierung
Bildgebendes Verfahren
Autorisierung
Wald <Graphentheorie>
Relativitätstheorie
Mailing-Liste
Routing
Quick-Sort
Endogene Variable
REST <Informatik>
Objekt <Kategorie>
Parametersystem
Mereologie

Metadaten

Formale Metadaten

Titel Building beautiful RESTful APIs using Flask
Serientitel EuroPython 2016
Teil 139
Anzahl der Teile 169
Autor Karzyński, Michał
Lizenz CC-Namensnennung - keine kommerzielle Nutzung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben
DOI 10.5446/21186
Herausgeber EuroPython
Erscheinungsjahr 2016
Sprache Englisch

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Michał Karzyński - Building beautiful RESTful APIs using Flask This talk demonstrates a technique for developing RESTful APIs using Flask and Flask-Restplus. These tools automate common API tasks such as: validating input, serializing output, routing requests to methods, and turning Python exceptions into HTTP responses. The final API comes with a Swagger interactive UI, which documents all endpoints and makes testing easy. The described tools tools provide just enough syntactic sugar to make your code readable, scalable and easy to maintain. ----- Modern software is powered by APIs. User facing apps may run in the browser or on mobile platforms, but they almost universally rely on data stored in the cloud. More often then not apps use a RESTful API to exchange data with the server. In my talk I will demonstrate a technique for developing RESTful APIs using the [Flask] micro-framework and [Flask-Restplus]. These powerful tools automate most common tasks associated with API development: validating input, serializing output, routing requests to methods, and turning Python exceptions into machine-readable HTTP responses. A Flask-Restplus API is fully documented by [Swagger] which lists all defined endpoints, their query parameters and the format of input and output JSON objects. Swagger generates an [interactive UI] for selecting options and easily testing queries. Flask and Flask-Restplus provide just enough syntactic sugar to make your code readable, scalable and easy to maintain. My presentation will give an overview of the features of Flask and Flask-Restplus; I will describe how easy it is to get started and discuss some best practices for building complex APIs using this approach. I will wrap up by briefly mentioning other components of the Flask ecosystem, which give this micro-framework power to match fully- loaded systems such as Django.

Zugehöriges Material

Ähnliche Filme

Loading...