We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Traveling through a secure API in Python

00:00

Formal Metadata

Title
Traveling through a secure API in Python
Title of Series
Number of Parts
115
Author
Contributors
License
CC Attribution - NonCommercial - ShareAlike 4.0 International:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
I like to remember the places I have been and I always liked the idea of having a map of those places, so as any developer would do, I built a web application for that. In this talk, we will see how you can use Python and Auth0 together to build your very own "Where Have I Been" map! I will walk you through all the steps we will need starting from scratch. From building the first API endpoints, protecting the endpoints that create new markers, all the data manipulation, and even deployment!
Temporal logicDrum memoryMaxima and minimaGoogolBitInformation securitySet (mathematics)Data miningInformationMultiplication signShared memoryPoint (geometry)Lattice (order)BootingFunctional (mathematics)Right angleWeb applicationLibrary (computing)Volume (thermodynamics)Identity managementMoment (mathematics)AreaSoftware developerCASE <Informatik>Computer fileEvent horizonSemiconductor memoryCodeUniform resource locatorToken ringTouchscreenZoom lensMereologyLevel (video gaming)Server (computing)Product (business)Radical (chemistry)Content (media)FamilyAuthorizationDivisorBuildingProcess (computing)Instance (computer science)InternetworkingWeb browserGame theoryLoginPlotterProjective planeLine (geometry)Data storage deviceDatabaseSingle sign-onObject (grammar)Flash memoryFreewareMobile appMultitier architecturePosition operatorPower (physics)TrailEmailWebsiteObject-oriented programmingControl flowMenu (computing)Web pageTable (information)Cartesian coordinate systemFrame problemSheaf (mathematics)Module (mathematics)Software testingSlide ruleType theoryHazard (2005 film)Different (Kate Ryan album)DebuggerElectric generatorVideoconferencingCloud computingSocial classMathematicsComplete metric spaceGoodness of fitAsynchronous Transfer ModeSubject indexingRow (database)AuthenticationView (database)NumberTwitterProgrammschleifeElectronic mailing listData managementPoint cloudRevision controlForm (programming)Online helpSampling (statistics)CodeSystem callReal numberCommon Language InfrastructureTask (computing)Variable (mathematics)WordIdentifiabilityVideo gameComputer virusMeeting/Interview
Temporal logicSoftware developerCodeProgrammschleifeObject-oriented programmingBuildingBitSoftware developerUniform resource locatorPoint cloudMereologyFamilyInformation securityNumberCodeMultiplication signLevel (video gaming)Set (mathematics)Line (geometry)Computer fileSubject indexingCloud computingData miningTouchscreenProcess (computing)Point (geometry)Moment (mathematics)CASE <Informatik>Library (computing)
Plane (geometry)Repository (publishing)Software repositoryLevel (video gaming)Content (media)Price indexLevel (video gaming)Library (computing)Computer fileVolume (thermodynamics)InformationRow (database)Lattice (order)Social classZoom lensFunctional (mathematics)CASE <Informatik>DivisorSet (mathematics)Shared memoryUniform resource locatorFreewareMathematicsWeb browserDifferent (Kate Ryan album)Token ringVideoconferencingTable (information)View (database)Frame problemSystem callObject (grammar)ExistenceDatabaseMultiplication signMoment (mathematics)Computer animation
Metropolitan area networkToken ringMach's principleAuthorizationCodeUser profileSource codeRepository (publishing)Directory serviceIntegrated development environmentHTTP cookieEmailLevel (video gaming)InformationOnline helpGame theoryRevision controlToken ringComputer fileWebsiteCodeMultiplication signProjective planeBitCASE <Informatik>AuthorizationEvent horizonRadical (chemistry)Server (computing)WordWeb 2.0IdentifiabilityWeb pageTask (computing)Software developerUniform resource locatorReal numberMenu (computing)NumberInternetworkingSheaf (mathematics)MereologyCartesian coordinate systemMobile app2 (number)EmailSoftware testingElectronic mailing listData managementRight angleForm (programming)Point (geometry)Semiconductor memorySampling (statistics)Moment (mathematics)Computer animation
Token ringEmailHTTP cookieIntegrated development environmentSoftware developerTemporal logicToken ringTwitterMultiplication signLevel (video gaming)Shared memorySlide ruleAuthorizationContent (media)Electric generatorProcess (computing)Uniform resource locatorDifferent (Kate Ryan album)CodeRight angleComputer animation
Embedded systemEmulationLibrary (computing)BitFreewareVolume (thermodynamics)Slide rulePosition operatorPower (physics)CodeMultiplication signMultitier architectureNumberAsynchronous Transfer ModeTrailRight angleAuthenticationCartesian coordinate systemComplete metric spaceSoftware developerLecture/ConferenceMeeting/Interview
Transcript: English(auto-generated)
All right. Welcome back. After the coffee break, we have Jessica here with me, calling from Brazil. And she is telling us a bit about traveling through a secure API in Python.
Hello. Hi. Great to have you here. And thank you for taking the time to prepare the talk and everything. You know, I'm very curious to hear about this, your talk and the security and
security eyes and all that kind of stuff. Oh, that's awesome. Thanks. Cool. All right. So I don't want to take much of your time. You have 30 minutes. OK, I will be here in the back. OK, thank you.
So welcome to traveling to a secure API with Python. Hi, my name is Jessica, as you probably know now, and I'm a senior developer advocate at Auth0. I'm also a podcaster and I have a podcast about data science here in Brazil called Pizza de Dados with a friend of mine, and I'm also an instructor about data
science in both Data Bootcamp, a bootcamp here in Brazil, and nicotine learning in the Brazilian library. So as I talked a lot about Brazil already, so I'm also a Pythonista and here's a picture of one of the Python Brazilians that I went to.
We have a lot of Pythonistas here. It's a very tight community and I love being part of this community. So this makes me really happy to actually be here in EuroPython because I love to connect with Pythonistas. So this is a great opportunity for me to meet you all watching from the other
side of the screen. So before we get started, I wanted to give you a sneak peek of what I'm going to show you, how you can build today. So this is the utmost goal of the stock. I'm a handsome person, so I prefer to actually give tutorials and workshops so that
we can have that moment together for talking and developing our skills and sharing knowledge and that I can make sure that you are following up in your understanding. But I could not pass this opportunity to be here today with you and talk about building APIs.
So because we are going to build an API, I'm going to start with foreign points and we are going to use Flask 2.0 that just came out. We are also going to do a little bit of data manipulation using pandas. The data scientists in me love pandas, so that is a great opportunity to use it.
And I'm also going to show you how you can protect your endpoints that does data manipulation so that only you can access that set of endpoints. And afterwards, because, well, you're going to build something, so you want to show your friends and colleagues and family. So let's apply that to the cloud.
I'm going to use miracle, but you could use whichever cloud service you want. So let's go to each of these steps. And whenever I'm trying to build something with code, I always go back to the basics. That's my first step always.
So this brings me to actually the place where I met Python and the Python community and became part of what I call my Python family, which was Hiberon Preto. So the first time that I actually given a talk in Hiberon Preto with a few friends of mine was about R and how to do the science stuff with R.
I was super, super nervous, but it was great. And that's actually where I learned the first time that everything that I did in R you could do in Python as well. So that opened up my eyes for a number of possibilities. So whenever I'm building something new, I always refer back to the basics that I
learned and I can build on top of the knowledge that I know, especially if I'm learning something new as I go. So talking about the basics, I always start my APIs with at least two endpoints. The first one would be the home endpoint, the one that it accesses by going to
the slash URL. And in this case, we're going to show them up. And the second one is the oops endpoint that I redirect people to in case something goes wrong during the processing or during the process of accessing my API.
And if you are new to Flask, this is what two basic endpoints would look like. Only a few lines of code. You have to import Flask object, extract your app, and then define both endpoints. And because I'm already using Flask 2.0, which I kind of love, I'm using the
ctac sugar to define which of the HTTP methods I'm going to use for accessing each of those endpoints. So in line seven, I have the decorator for getting method for the home endpoint and so on and so forth. And those two endpoints are going to serve two index files, two HTML files.
One index file for the home, that's where my map will be. And the other one will be the oops file. At this point, these oops files just say, hey, if something went wrong, go back to home. So it's very simple HTML.
And after I have my basic endpoints, I can run my API. What I do is I build the things that are going to handle data. So the first endpoint that I usually do is a ping endpoint. In this case, my ping endpoint will help me regenerate my map.
So while I'm developing, I might need to regenerate the map a couple of times. So why not have an endpoint that does that for me instead of me actually running the code every time that I need to have a new map? So in this method, in this endpoint, actually, excuse me, I have a method that's called createMap.
And this is the method that does the magic of actually creating the map. And we are going to see that in a little bit, so don't worry. And the second protected endpoint, well, right now it's not protected, but it will be protected in the future, is called places. So what places does it accept a post request?
And it takes the data from the body of this request and creates a new pinpoint location on my map. And it does that by doing a little bit of data manipulation using pandas and then regenerating the map.
And I've been talking about data a little bit. So I'm a data scientist, at least I was a data scientist until I joined at zero. But it's not that I left a job that had the data science title, that I stopped being a data scientist. So I always think about the data that I have.
And this brings me back to one time that I went to Austria to record a course. So I always think back to this moment in time, because, well, until then, I used to think that I would speak like a lot from conferences calls and from programming sessions
and all the meetings in my day to day because I was already working remote. So I had a lot of video conferences to do. I always end up my day saying, well, I talked a lot today, so I'm feeling tired from talking if that's possible.
But once I went to Austria to record this course, I found out that actually what happens is you don't talk as much as you thought, because during the recording process, I had to speak actually eight hours a day for practicing the classes that I was going to record and actually recording the classes.
So it took me actually understanding better my data to realize that, well, I may talk a lot, but not as much as I would talk if I were recording a course again. So data is something that is very special to me, right?
The data science in me always loves to look at data and looking at the data that I had because I wanted to show this data in a very interesting way, in this case, a map. I would have to make a collection of the cities that I wanted to pinpoint.
So I built up the CSV file with some of the cities that I've been to and with their names and their latitude and longitude. And you see why we need this. So the first thing that I need after having my data is actually
loading this data from somewhere. In this case, I'm using everything free. So my data is stored in GitHub and is loaded from Heroku from GitHub. And the only thing is I have to log into GitHub to get this data.
So I used PyGitHub to help me out. I generated an access token and this library can do its magic by reading this CSV. And after that, what I need is to pass this CSV information into pandas, our great data science library to deal with table data.
And then I generate that data frame from pandas that I can use and look over to get the information for each of the city. Which brings me to the map, right? Because, well, I can't put pinpoints in a map that doesn't exist.
So I need to create the map and I created a function for that. And it is using volume. So volume is a library that relies on OpenStreetMap for creating maps. And the only thing it needs to start is a location on the map to center the map around.
So I created a function that returns me a centered map with a zoom factor of three. And the zoom factor can be a little tricky because you have to try a little different zoom factors to see which one works best for your use case. So the zoom factor of three actually gives me that pretty view on my browser
that shows all the locations that I have in my data set. And now that I have my map, I can actually create the markers for each of the city. So creating the markers involves only having a location.
But because I want this map to be friendly to other people that might not know the location of each city that I've been to, like my friends, I also added the information for the city name on each marker. So the marker is built like this. You import the marker object from the volume library.
You give it a location, much as like the map we just did. And then you can add other levels of information like coloring for each of the marker. You can add a name or HTML inside the marker so that you can see different things.
In this case, I went with the most simple one. I give it the location and the name so that people can click on each of the markers and see where was the city, right? And after I have everything, I will also want to save my data because, well,
I intend to visit the whole world if I can to share knowledge and meet other people, right? So because of that, I know that I'm going to need to add more cities to my data set. And I just don't want to go into GitHub to do that. I can if I want to, but I also want to be able to add cities by accessing my API.
So I created the same method that actually dumps the information, the updated information into GitHub, the same way I can read from GitHub. And once I've got all of these helper functions done,
I can put it all together into the two main functions that I'm using. The one for creating the map that I use while regenerating the map on the ping endpoint, and the other one for updating the data set and then regenerating the map. So I have here my create map that calls all the other functions that I already have.
And I chose to do this this way because then my endpoint doesn't have to suffer any changes in case, for instance, I decide to change the way that I store data from GitHub to, I don't know, a SQL database or something.
So here we go. After that, I also, oops, I have to go back here. Okay, here we go. I also created the create new place. This only does like add the information for the new city to my data set. And I have to actually call the create new map again if I need to.
And now I have the protection part. So one thing that happened to me in my first big Python event, it was a Python Brazil on the very first day and I kind of twisted my ankle.
And you can see in this picture that it wasn't ideal, but I could always rely on my friends because, well, this is right after I twisted the ankle and went to the hospital to have it immobilized and my friends helped me out through the whole event. I didn't miss any talks that I wanted to watch.
I didn't miss any happy hours as you can see from all the fun that we have in Brazil when we have Python events, because, well, it's a gathering that is very friendly and we all want to enjoy everybody so much that we always have time to have fun
a little bit after each of the talks stays. So the same way that I relied on my friends during Python Brazil one time ago, you can also rely on Auth0 to protect the endpoints. And I'm speaking about Auth0 because actually it is really simple to protect endpoints with Auth0.
So the first thing that you would need is actually an account on Auth0. And after you log into that account, you can access your dashboard and you probably see something like I'm showing right here in this picture. It is the very getting started page. It links you to a bunch of quick sites that we have.
But right now, what we need is to protect an API. So on your menu on the left side, you can access your applications section. And in the applications, you can set up a number of applications. But in this case, we are going to choose APIs. Well, because we are protecting an API.
And after you click that, you will see a list of APIs available to you. Here, I have two APIs, the Auth0 Management API that comes with any account that you make on Auth0. And the second one, Base API, is actually something that I have for another code sample that I was working on.
So for this API, we're going to create a new one. And you can do that by clicking the Create API button on the top right corner. And then you see a form to fill with the information for your API. And, well, my advice to you is that you give a very representative name of your API.
Because once you have multiple projects going on, you might need help knowing which one refers to each one. So in this case, I gave it the name, Where Have I Been, because, well, I'm trying to build a Where Have I Been map. And the identifier that we are going to use later and that you can't change.
I just chose the first letter of each word and went with it. And it can be anything that you want to. So after you click the Create button, you'll see the information for starting with your API.
And you can check it out, the quick starts, and you can check out the settings and permissions. But that's it. You don't need to do anything else in the dashboard. You are good to go. Well, actually, you need to update your code so that your code is protected, right? So to do that, you can go to the task tab in the dashboard to actually get an access token.
And there are two ways that you can get this access token. You can either do a request with this URL example that we got here, or you can call for the access token right below that. So after you have everything set up on the dashboard, you go back to your code,
and you're going to need two decorators on each of the protected endpoints. And the first one is the cross-origin, and it comes from the Flask-force package. And it's going to make sure that I have the headers that I need, like the content type, who is going to be application JSON, and the authorization header, which you will have my access token.
And the second one, the requires auth, is actually provided to you by Auth0. So you can just copy the code and put it on your modules, whichever way you prefer, and then you can use it. And just so that you know, you actually can access this code and look it over in our quick starts
for how to create an API with Python and protect it with Auth0. And of course, like I said, you can copy the access token from the test tab,
or you can see the code for making the request. Just keep that in mind because you're going to need that access token afterwards. So at this moment in time, I have everything that I need, or at least almost everything that I need for deploying my API.
I have all my code, I have my protected endpoints, and I have my Auth0 account set up. And you may be wondering, OK, so what else is required for deploying? And every time that I get to this point in my development,
I remember one time that I was not ready at all for an event that I went to. So in Brazil, we have what's called Campus Party. And Campus Party is a technology event. Today, it used to be about gaming and spending a whole lot of time with fast internet.
But today is about technology as well. So I was invited to talk at Campus Party one time about a project I was working on at the time for civic tech in Brazil. And I thought, well, why not? And the packaging for going to the event was actually staying in the camping area.
I should have guessed, but for some reason, I didn't know I had to bring camping gear. Well, they give you the tent, but I didn't know for some reason that I would have to bring, I don't know, an air mattress or a sleeping bag.
So I was so not ready for the moment. Could you guess that? It's a camping event. Come on. But whenever I think about that, I always have a fond memory on how I could rely on my friends again, because they kind of saved me, gave me all the material that I needed to be comfortable at the event
and enjoy meeting all the people and talking about technology. And in the case for hero code, the preparation package, let's say like this, is you have to have two files. The first file is a proc file. And while you're developing with Flask, you're probably going to run the development server by running Flask run on your terminal.
But that's not ready for production. So you need to actually have a new server that is production ready. In this case, I'm using unicorn. And also, you need to tell hero code how to run your app, right? So the proc file does that job. So it tells it, hey, hero code,
I have a web application, and the way to run it is a unicorn app. And other than that, you also need a PIP file. And the PIP file has all the packages that is going to be fired to run your API, where to download them from,
and what Python version you are using. So after you commit that, you are pretty much set. You just have to log into hero code or pay your account, download the hero code CLI, and push your code to the cloud, right? And it is supposed to be very straightforward.
Hero code tells you how to do everything in what you do all of the steps. And that's pretty much it. So now you're saying, okay, cool, you showed all the code, you showed how to set up everything. So let's see that in real life, right? So part of my also preparation package
is actually using a tool called Insomnia. And Insomnia does a lot for me. You can set up variables, and you can set up your request so that you can just run through over them, and everything will be ready for you. So for example, I have my home endpoint set up. So I can do a request
to my base URL, in this case, the hero code page. So if I send this request, and it might take a little while because hero code can take a little while to reply, depending on the time. Let's see if it goes. You should see something like my map that I have right here. So that's what you should see inside Insomnia.
And there we go. It only shows you the map, right? It took a little while because it was first time loading this today. And I also have other requests for my protected endpoints here.
But before I can run them, I need to access Auth0. Of course, I could copy my access token from the dashboard, but I like to have my access token being obtained by doing a request. So I do a post to the Auth0 authorization endpoint, and I get my access token.
And this is stored inside a variable that I can reuse for my other request. So I have my request set up here that I can actually check the access token. And you can see here is the same value that I obtained from my last request. So if I do a generate new map request that is going
to access my ping endpoint and rerun the process for regenerating the map. And this can take a while, but once it is done, it shows my map again. Now, this has no difference between the things that I was showing on my browser, because, well, there is no new cities in there, right?
So if you are creating your first map, I have a suggestion for you. Why not start your map with the city that you are right now watching the stock? So in my case, I met someone just there, which is a city right here in the south of Brazil. And this is the latitude and longitude.
And you can access these values from either Google Maps or street maps very easily. So if I do this request, and it takes a while because it has to run all the code and regenerate my map. And if I zoom in here, you should see a location placed here. Oh, and it's cached,
because I did this request before. So I need to send it over again. And it's going to take a while. And now I have someone just there in there. So you can see Florianopolis where I
said my ankle. And you can see so she said that is really close to it. So that's it. Oh, let me skip over this. That's all that I had for today. I was really happy to be here and join you all and share this content. You can find me on all of the
internet, searching for Justin Peral on Twitter or anything else. And I'm going to share this slide so you can access the code. That's it. Fantastic, Jessica. Great talk.
I really liked it. I actually have a very similar application without the protection, which I should I should look into about tapas places I've been to, you know. Oh, that's so awesome. What a great idea. It's not as exotic as you. It's just like food and drinking.
Oh, I love food. So I totally understand and eat. Fantastic. Fantastic. So great. Great thing. Great talk. Fantastic. Thank you. Thank you. So will the code be available? You mentioned something that you are going to put the
code up. Yes, the code is available actually is on private mode on GitHub, but it's going to be available right after this talk. And I'm going to share this slide so anybody can access it. Fantastic. Yeah, because it would be nice also to explore a little bit the libraries that you use for this volume library and Auth0. Can you also mention something a little bit more about,
you know, Auth0 and how it works? So I guess you showed the authentication using a token for an API. What other modes are there that we could use in, I don't know, Flask or whatever?
Any other modes. So everything you can use on Auth0. Auth0 is supposed to make our like developers like me and you lives easier. So we have a very complete package of libraries and SDKs that you can use either in the back end, like Python, for instance, or in the front
end, if you are a JavaScript person or a full stack developer, you can use Auth0 in any number of ways. And SSL, for instance, like using social login, you can use that too. So anything is possible if you use Auth0. Fantastic. Fantastic. And just one last question and
we are running out of time and I'm using my position of power here to just ask you questions. But I guess this is something that folks would also be interested in. Is there like a free tier account, Auth0 or something that we can use to test? Yes, we have a free tier account and
actually this was using everything free tier like GitHub, Auth0 and Heroku and everything else. And just so that I can enjoy this time, if you have any questions more about Auth0, Python or everything that I did on the stack, you can join me either on the Auth0 booth or during the
session we have for this track. Fantastic. Thank you so much, Jessica. Thank you, Francesco. It was nice to be here.