API Series #2 - Building an API with Flask in Python
Key Takeaways
This video series demonstrates how to build a simple API using Flask in Python, covering topics such as API design, data retrieval and manipulation, and error handling. The video provides a step-by-step guide on how to create endpoints, handle HTTP requests, and interact with CSV files.
Full Transcript
hi in this video we are going to explore how we can put together a pretty simple api using flask now what we're going to do is go through and build essentially what you can see here so all this code here is a single api we're not going to go through all of it in in this one video but we're going to go through the essentials and we're going to step by step put an api together that is going to look very similar to this now what this api is doing is pulling information from these two csv files and either presenting that information to us that data allowing us to modify allowing us to add new entries or allowing us to delete it so we we get to use get post put and delete methods now if you are following along with this tutorial you'll probably want this data so you can get it using this code over here so over here we have i'll make sure there's a link to this in the description so you can get it all we're doing is downloading the code or all those two data files from here and then storing it in a local directory i mean you can you can change that directory to whatever you want of course inside those two files inside those two files we have locations here which is just a list of i think these are actually real coffee uh cafes but i i put this i made this csv quite a long time ago so i'm not 100 sure and then over here we just have some made up user data as well and the end result will be something like this so this is uh this is a program called insomnia i'll leave a download link to that in the description uh but it just allows us to send api requests very easily so i'm gonna send an api request to this address here which is the api i just showed you and it's a user's endpoint we will have two endpoints which are essentially just uh separations of the api so users and that's going to return all the users data and then we also have locations and we'll send that as well and we return all the locations now we're going to start from scratch and the first thing that we'll need to do is import everything we need so we will need to import flask so from flask import flask we'll also need to import flask restful so this is another flash library that gives us a few very useful tools for building an api so right from flask restful import resource api and rec pass now specific to what we're doing here we will also want to import pandas and import ast now you will probably have to pip and saw these as well so uh the pip for those is pip and salt flask and flush restful nothing nothing weird there all right so the first thing we need to do is initialize our flask app and then initialize our flask api so we do that so this is typical flash here so we write flask name and then the api is api equals api app okay super easy now we we already touched on it but our app is going to have two different endpoints so we're going to have the user's endpoint and we're also going to have the locations endpoint and we're going to go through building the user's endpoint but i will you'll be able to find the code for both of those in the description but the way that we separate both of these is we use a class object so we're going to create our use class first so we write class users and then to initialize this as a endpoint for our api we actually need to pass the resource object into it that will inherit the resource object and expose it to different like http requests like like get post and so on for now we're not going to add anything in there but to make sure that endpoint is added to our ar api we need to write api add resource and then we need to specify the web address of this or the or the it's almost like a page of web address that the resource or endpoint will be at so we'll say users which is our class and then the actual endpoint location which is users okay so this this is saying i want you to map the class users here to this place in our in our api so our web address so if for example the api was located at let's say api.com this resource would be located at api.com users okay and we'll also create another one although we're not going to fill it out in this video that will be called locations again exact same thing again resource we'll just pass for now and we'll copy that and do the same for resol for locations okay now that's sort of the for the the structure or the very high level structure of our api cell but we so what i like to do is whilst we are building or writing the code for our api i like to also test it so as we go along i think it makes things a lot easier so to run our api we need to write this if name is equal to main we write app dot run okay is that easy and now what we can do is just press the execute button up here okay okay so we got this error because i okay i don't know why i did that so this is this needs to be the class not not a string of the class um okay so now let's run again it should work okay so we get this this is a development server do not use it in production environment that's fine because we're just testing it and then we can see this is running at this address okay so if we if we take this we'll copy it and we're going to take it over into insomnia okay and i'll just clear everything that i was doing before and we'll go to here okay and if we if we send this we won't return anything yet so we'll just get this not found but if we if we go to users we should at least return this internal server error so this means that okay we are not getting anything back because there's an error on server side so in our api but there is something there you know so before when we just had this so remember we have those two endpoints we're not actually using the base url so there's not actually anything there we get this and not found because there just isn't anything there if we type in locations or users we will return this internal server now we're getting this because we we haven't written any code so it doesn't know what to do when we send that request so let's go back to our code and we'll start writing something so first thing i want to do is we'll define a get request so right find get bus self and in here what i want to do is load the user's csv so to to get that i'm going to write users path so this is the specific directory that i have stored my user's data of course it might be different for you and what i'm going to do is down here i'm going to use pandas to just read in that data whenever i call this get request i'm going to read it in so this is it's very similar to if we for example had a database on a server somewhere when the api gets a request it would read that data quickly and return it to us so this is a very simple version of that so we're going to do data equals pd.read csv and we just go user's path and hopefully that's the right path i think it is so we can see so if i come up to here yes we have data so i yes that should be fine uses csv cool and then what we want to do we can't pass a we can't pass a panda a date frame object through an api so we need to convert this into a dictionary so we write data.to date now what i want to do is return we want to return the data so we're going to write data which is equal to data our dictionary and we're going to return the 200 code which means the the api request was successful here's your data okay i'll save that and i believe it should it should update automatically let me let me check so come over here let's send that again to users okay no so i think we need we need to restart the api so come over here let me here i'm just going to ctrl c and run it again now you can you can turn debug mode on so i think that will automatically reload everything uh so to let's do that first so down here in app run which is going to set debug equals true save that i'm going to press ctrl c down here and execute again and now when we make changes it should reload automatically so come over here let's send that request again now we see user path is not defined so [Music] see why that is wrong so it's user's path so i'll save that and i should reload automatically let's try again okay perfect so now we get a 200 response there we get all of our users data okay so we're just returning that data frame in a dictionary format okay cool so that's our get request let's move on to let's put requests i think so adding more data okay so this time we're going to need to do is so we're using a post request said put a second ago i'm in posts um and [Music] in here the first thing we need to do is we need to retrieve information from the user that they want to upload so the first thing we need to think about here is we are trying to get data from the user so they are going to send us like a new entry so what did we have before in our users uh we have user id name city locations okay so we want the user to be able to add a new row so each one of these is essentially a row in a data frame so we have locations city name and user id now we want the user to be able to add locations or location locations name and city now the i think the the user id we we don't really want the the user isn't going to add that that's going to be generated automatically so we ignore that but we do want the user to be able to pass those three things now to do that we're going to use the rec passer so request pass that we use up here and to initialize that we need to write parser equals request sorry what is up here uh rec pass sorry wreck pass dot request passer here okay that initializes our password and what this is going to do is when we add arguments into the into the requests this is going to read them and what we're going to do is pass them out into variables so we are going to within our within this request we want to allow those three so location name and city so right parser add argument and this one will be location and we're just going to do one location at time so do location id and then of course we use a put request later if they want to add more locations you say required is true because we do need to add one of these and the the type this is a integer so we write okay the we need to add another one i'm just going to copy this so let's copy here here and we have name and city name city uh and the type is for both of those strings which i think might be the default so we probably don't even need to to include that type string there but it is there so i'll leave it so now we have the the three arguments that our user can use to post information to our api and what we need to do to extract whatever the user has sent us is we we do this so we're going to extract them into this dictionary here which is called args and we write parser pass odds like that okay so now we have those arguments and let's first just make sure this is working so i want to just i'm going to return what we what we just tried to send there so let's return to location lock equals arbs location id name and the city okay so let's just make sure it's actually working and we'll say 200 save it and that should reload automatically let's go to insomnia and we are sending a post request here so post we have users we enter this question mark so this allows us to start adding our parameters so location id which is going to be equal to i'm going to say five and so we we added the ampersand symbol there to add another parameter so location id and what are the other ones user user or name um james it's me and for the city oh let's put london okay send that cool and then we we we're just returning that request back to us you notice here we put lock uh not location id so we can tell it's not just returning what we sent it's returning what we have processed through our function and returned back to ourselves okay cool so now we know we're passing those arguments correctly now let's use them so again what i want to do is read our data so we do data equals data pandas dot read csv again and we're reading the user's path okay so user's path and we're doing users here so actually do we want location in there at all i don't know um yeah maybe so no let's let's say the user can specify that user id uh oh we're not returning anymore so let's remove that so i want the user to i want to be able to post this because then if we have a duplicate of a previous user id we're not we can say we can check if that already exists in the data or not which we'll do now so write if args user id in the data that we just loaded so in data is it user id i think i'm sure it must be okay i think it's i want to return an error message saying this already exists it's right message and all we do is write arbs user id already exists and what we'll return here is the 409 code which indicates that there's some sort of conflict uh when there is a conflict we we already this user idr already exists so we're saying there's conflict you can't you can't you know create a new one it it's already there if it doesn't already exist and that's great and we go ahead and we create that new user id so all we do is write data equals data.append and then we're just appending the new data that we've retrieved from our ops so it's going to be we need user id which is going to be arbs user id let me copy this make it a little bit quicker for locations it's just empty for now city and we have name okay and then we need to i think we need to ignore yes ignore index uh true true sorry okay and then we'll save that data so to csv it is it uses path and i'm gonna set index equals false so we're not saving the index the row numbers and then i just want to return i want to return that data again we can't return a data frame we need to convert it into a dictionary so write to dict and it's a 200 response so i'm gonna save that let's test it see if it works so i'm going to let's see modify this to user id now send that internal server error so let's see date frame no attribute to date so i need to add an underscore save again and let's send that again okay so now we can see we have more um items in there the only thing is i've added five for all of them oh did i it's in the code right what did i do yeah very smart okay so change that name and this is city now one other thing is that these are all this should also be a string one thing i notice and this should also be a string i'm going to leave it for now it's fine so let me send that again five already exists because so at least we know that our conflict code works so let's create another one number six i'm going to call this gym and let's go again okay so now we've created number six as well uh did we create gosh we created a few there didn't we oops so yeah now we've now we have created number six here which is jim lives in london his user ide is six okay so i mean formatting isn't perfect but that's good for now we've created our first post request okay so it's it's pretty annoying that we have those kind of messy entries that we added to our data sets or date frame so what we really could do with having in our api is a way to actually delete those so let's go ahead and build that so we need to first define a delete function method and all we really need here is to say okay which which entry do you want to delete so we don't need to have a name or a city or anything we just want the user id so we'll copy that into here so we we pass the input from the user and then we say okay add argument user id that's all we need we don't need anything else uh and then and then what we need to do is pass those as well so uh just like before passer pass args yeah there we go so now we have so at this point the user has given us a user id that they want to delete and we need to go ahead and delete that so to delete it first we need to say okay does it does it exist so we say if args user id is in our data so we need to load the data first so let me let me load it here okay so if that is in data user id then then we can go ahead and delete it and to do that we're just going to use the typical like pandas data frame logic so we just write data equals data data user id and we just want to select the rows that are not equal to the user id that we just pulled in so the arbs user id right so that's just going to return all of the rows set from the one that we've specified okay so we've deleted that now we just need to save that to file again to csv it is i keep getting the the variables users path and then indexes false okay so we've opened the file deleted the entry saved it back to csv uh if we have done all that we can return to the user at 200 codes so we'll just return let's return all the data again and we don't need to do this every time we could just return you know a statement saying hey you've deleted it everything so i'm just going to return so we can see what we're actually doing in reality probably i'm pretty sure you don't want to wouldn't want to actually do this but i suppose it depends maybe maybe you would who knows so return 200 code because it's successful now indicates that the user id does not exist here we want to say okay we want to check what we've already checked if it exists and then from there we're just like okay it doesn't exist what are you doing so we just return we say what did we use before when we sent a message messages message okay cool message and the message is going to be uh user id does not exist something along those lines so args user id um does not exist let me format it a little nicer and then here we need to add the code which is i suppose not found so 404 okay so i think that's it really um so let's save it again it should reload automatically head over to insomnia let's again so let's go to users we're just going to look at what we have so sorry get users what do we get we we have all these now we want to delete user ids four and five okay these two are messy we don't want those so uh we want to specify okay user id we don't want four so we change that to a delete request we don't want four let's send that see what happens um why why did that not change data i didn't that change use id is it because because this needs to be a string i think oops okay i think uh yeah probably [Music] let me try again send no still nothing okay so that took me far too long to actually uh figure out what was wrong but there wasn't anything wrong the there was a the string issue uh so we did need to convert over to a string to compare them uh but also so what i was doing here was reading the the key value here so the row number and thinking forwards your user id is it's not uh we have we have two fives that we messed up and made those earlier so we we there is no four for us to remove now we don't need to don't need to worry about it so let's test it with five instead which are the the two messy ones that we need to remove so let's send that and now you can see that we've actually removed those entries so that's pretty good now the one thing i did also notice is if i try and send that again we do get the 404 not found so that's that's pretty cool right we've got everything that we would expect with it now i think that's it for the code the only other thing i wanted to show you was this other so this is the actual full api script here so in here i also included a another another method here or another endpoint locations and we run that and we can mess around with the cafe locations as well so but that's everything so i think there's nothing i just want to cover in this video so we'll leave it there so thank you very much for watching i hope it's been useful and i'll see you again in the next one bye
Original Description
Next video - how to deploy to the cloud: https://youtu.be/3fsIcMgUOY8
How can we set up a way to communicate from one software instance to another? It sounds simple, and - to be completely honest - it is.
All we need is an API.
An API (Application Programming Interface) is a simple interface that defines the types of requests (demands/questions, etc.) that can be made, how they are made, and how they are processed.
In our case, we will be building an API that allows us to send a range of GET/POST/PUT/PATCH/DELETE requests (more on this later), to different endpoints, and return or modify data connected to our API.
We will be using the Flask framework to create our API and Insomnia to test it.
🤖 70% Discount on the NLP With Transformers in Python course:
https://bit.ly/3DFvvY5
🕹️ Medium article:
https://towardsdatascience.com/the-right-way-to-build-an-api-with-python-cd08ab285f8f
🎉 Subscribe for Article and Video Updates!
https://jamescalam.medium.com/subscribe
https://medium.com/@jamescalam/membership
👾 Discord:
https://discord.gg/c5QtDB9RAP
Free article link:
https://towardsdatascience.com/the-right-way-to-build-an-api-with-python-cd08ab285f8f?sk=6e2dda4c8b6012767114e12ff34b1464
Download Insomnia:
https://insomnia.rest/download
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from James Briggs · James Briggs · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Stoic Philosophy Text Generation with TensorFlow
James Briggs
How to Build TensorFlow Pipelines with tf.data.Dataset
James Briggs
Every New Feature in Python 3.10.0a2
James Briggs
How-to Build a Transformer for Language Classification in TensorFlow
James Briggs
How-to use the Kaggle API in Python
James Briggs
Language Generation with OpenAI's GPT-2 in Python
James Briggs
Text Summarization with Google AI's T5 in Python
James Briggs
How-to do Sentiment Analysis with Flair in Python
James Briggs
Python Environment Setup for Machine Learning
James Briggs
Sequential Model - TensorFlow Essentials #1
James Briggs
Functional API - TensorFlow Essentials #2
James Briggs
Training Parameters - TensorFlow Essentials #3
James Briggs
Input Data Pipelines - TensorFlow Essentials #4
James Briggs
6 of Python's Newest and Best Features (3.7-3.9)
James Briggs
Novice to Advanced RegEx in Less-than 30 Minutes + Python
James Briggs
Building a PlotLy $GME Chart in Python
James Briggs
How-to Use The Reddit API in Python
James Briggs
How to Build Custom Q&A Transformer Models in Python
James Briggs
How to Build Q&A Models in Python (Transformers)
James Briggs
How-to Decode Outputs From NLP Models (Python)
James Briggs
Identify Stocks on Reddit with SpaCy (NER in Python)
James Briggs
Sentiment Analysis on ANY Length of Text With Transformers (Python)
James Briggs
Unicode Normalization for NLP in Python
James Briggs
The NEW Match-Case Statement in Python 3.10
James Briggs
Multi-Class Language Classification With BERT in TensorFlow
James Briggs
How to Build Python Packages for Pip
James Briggs
How-to Structure a Q&A ML App
James Briggs
How to Index Q&A Data With Haystack and Elasticsearch
James Briggs
Q&A Document Retrieval With DPR
James Briggs
How to Use Type Annotations in Python
James Briggs
Extractive Q&A With Haystack and FastAPI in Python
James Briggs
Sentence Similarity With Sentence-Transformers in Python
James Briggs
Sentence Similarity With Transformers and PyTorch (Python)
James Briggs
NER With Transformers and spaCy (Python)
James Briggs
Training BERT #1 - Masked-Language Modeling (MLM)
James Briggs
Training BERT #2 - Train With Masked-Language Modeling (MLM)
James Briggs
Training BERT #3 - Next Sentence Prediction (NSP)
James Briggs
Training BERT #4 - Train With Next Sentence Prediction (NSP)
James Briggs
FREE 11 Hour NLP Transformers Course (Next 3 Days Only)
James Briggs
New Features in Python 3.10
James Briggs
Training BERT #5 - Training With BertForPretraining
James Briggs
How-to Use HuggingFace's Datasets - Transformers From Scratch #1
James Briggs
Build a Custom Transformer Tokenizer - Transformers From Scratch #2
James Briggs
3 Traditional Methods for Similarity Search (Jaccard, w-shingling, Levenshtein)
James Briggs
3 Vector-based Methods for Similarity Search (TF-IDF, BM25, SBERT)
James Briggs
Building MLM Training Input Pipeline - Transformers From Scratch #3
James Briggs
Training and Testing an Italian BERT - Transformers From Scratch #4
James Briggs
Faiss - Introduction to Similarity Search
James Briggs
Angular App Setup With Material - Stoic Q&A #5
James Briggs
Why are there so many Tokenization methods in HF Transformers?
James Briggs
Choosing Indexes for Similarity Search (Faiss in Python)
James Briggs
Locality Sensitive Hashing (LSH) for Search with Shingling + MinHashing (Python)
James Briggs
How LSH Random Projection works in search (+Python)
James Briggs
IndexLSH for Fast Similarity Search in Faiss
James Briggs
Faiss - Vector Compression with PQ and IVFPQ (in Python)
James Briggs
Product Quantization for Vector Similarity Search (+ Python)
James Briggs
How to Build a Bert WordPiece Tokenizer in Python and HuggingFace
James Briggs
Metadata Filtering for Vector Search + Latest Filter Tech
James Briggs
Build NLP Pipelines with HuggingFace Datasets
James Briggs
Composite Indexes and the Faiss Index Factory
James Briggs
More on: LLM Foundations
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
The Only Git Commands You Actually Need — 47 Patterns for Daily Work
Dev.to · The AI producer
Common Next.js Errors (and How I Solved Them)
Dev.to · gary killen
Applying Scalability in Backend (CodeBuddy)
Medium · LLM
Why Every Backend Developer Should Learn Nginx Before Going to Production
Medium · DevOps
🎓
Tutor Explanation
DeepCamp AI