Hello,
Once again I cannot believe I am already this far into the program. I was just writing my first blog yesterday, and Now there's only 4 weeks left of the program. Insane. Anyway, let's learn about Flask today
APIs
First you might be asking, what is an API
? Why are they important? an API(Application Programming Interface) is a practical way for developers for populate the frontend of a website with dataset. There are hundreds of thousands to millions of apis available made by other people, all with their own unique dataset. For example, I can access all the characters in a Lord of the Rings api or all the different plants in a Ecosystem api. the usefulness of api's depends on how big the dataset is, how easy it is to navigate, and how well the documentation for the api is. A practical example of how a developer would use an api would be me building a website where you can see the statistics of all your social media pages, so I would grab data from the apis of the respective websites (Facebook, Instagram, Youtube, Reddit, etc.) and then take that data and display that on my website. Apis are not designed for normal people to use, but for developers like myself.
Flask
Apis are a big part in where Flask
comes in. What if we have our own database? We can't access that database from the frontend directly, so we can build our own API. Last post I talked about Python
, SQL
and relationships. Flask in itself is not a whole new language, but builds upon those so we can put it all together. There are two different versions of Flask; Flask-Restful, and Flask-Rest. They both perform the same actions, just with different syntax. I personally prefer Flask-Rest, so from this point I will be showing code examples using that syntax. Let me show you some code:
@app.route(/users, methods={"GET",})
def get_users():
users = Users.query.all()
return users.to_dict(), 200
This is a very basic route. When we define @app.route, the /users
indicates one route we've defined, and Get
means we can only GET data from this route. For example, if we created an API hosted on a website Flatiron.com/users, we would get all the users. users
within the code querys the database, and when we run to_dict()
, that turns the data into a dictionary, which is a datatype in Python. You might be wondering, what does the 200 do? With HTTP, they have something called status codes
for us developers. One of the most common error codes you might recognize is 404 Error not found. There is also other different codes;
- 200 OK
- 201 Created
- 400 Bad Request
- 401 Unauthorized
- 403 Forbidden
- 500 Internal Server
Full Functioning Routes
Often you as a user will not need to know these codes because only us developers need to know it and it helps with bug-fixing. There are many different methods we can add in routes, but there are 4 major ones;
- GET
- PATCH
- POST
- DELETE
You can probably assume what these do. GET just retrieves data, PATCH updates data, POST adds new data, and DELETE, deletes data(duh). Let us create a new route that allows us to do all 4 methods to a /cars route;
@app.route('/cars/<int:id>', methods=["GET", "POST", "PATCH", "DELETE"])
def cars(id):
car = CAR.query.filter(Car.id == id).first()
if request.method == "GET":
cars = Cars.query.all()
return cars.to_dict(), 200
elif request.method == "POST":
data = request.get_json()
new_car = CAR(
name=data['name'],
year=data['year'],
company=data['company']
)
db.session.add(new_car)
db.session.commit()
return new_car.to_dict(), 201
elif request.method == "PATCH":
data = request.get_json()
for item in data:
setattr(car, item, data[item])
db.session.add(car)
db.session.commit()
return car.to_dict(), 202
elif request.method == "DELETE":
db.session.delete(car)
db.session.commit()
return {}, 204
In this route, we have done full CRUD(Create, Read, Update, Delete). Unless if you build an API, you usually only have access to read it. Now that we have build this api, we can build our frontend to access the data:
function cars(id){
fetch('/api/cars/${id}')
.then(r=> r.json())
.then(data => {
someState(data)
}
}
return (
<div>
<h1 onClick={() => cars()}>Click me!</h1>
</div>
Bringing all my work thus far at flatiron to full circle. I have learned so much the past 11 weeks, and I cannot wait to learn even more for my phase 5 project! See you guys next time.
Top comments (0)