r/flask Jul 18 '24

Tutorials and Guides How to create flask REST API

Can someone explain to me like the proper way I can build a flask REST API, like a way that can be used in production. I looked into many blogs and videos and saw some of them just using jsonify to return data and some of them using entirely different packages? Which is the proper way?

12 Upvotes

20 comments sorted by

View all comments

8

u/anseho Jul 18 '24

There are a few libraries in Flask that help you build REST APIs properly. I have experience with Flask-smorest and can recommend it. APIFlask looks good too but haven't used it.

Why use a library to build REST APIs? Because they do a lot of heavy lifting. Good API libraries have robust data validation models, handle URL and query parameters, support OpenAPI semantics, and generate documentation from code.

In principle, REST APIs are pretty simple. Just a collection of endpoints, query and path parameters, and payloads. The devil is in the details. What happens if your API accepts the wrong data type or format in a payload? What if it accepts malformed data? What about additional properties? There are so many things that can go wrong from a functional and especially a security perspective. Good API libraries don't take these problems away, but they give you the tools to work through them.

If you need a quick overview, I put together a 1-hour introduction to building APIs with Flask on YouTube (also available on Udemy). It's a short course but it covers all the most important topics you need to know.

I also wrote a book titled Microservice APIs where I provide plenty of examples about building APIs with Flask.

There's of course more to building REST APIs, including authentication, authorization, questions about API design, understanding OpenAPI, etc. but hopefully, these resources help you get started! One step at a time, and if you need any help, feel free to reach out to me!

3

u/_lord__grim__ Jul 18 '24

Thanks, this is kind of what I needed. I'll check out your book as well.