(This page has no text content)
Getting started with FastApi Here continue your roadmap in the development of web applications in Python with FastApi Andrés Cruz Yoris This version was released: 2023-08-03
Tweet about the book! Please help promote this book. The suggested tweet for this book is: I just bought the book "First steps with FastApi " from @LibreDesarrollo! Get your copy at: https://www.desarrollolibre.net/libros/libro-primeros-pasos-con-fastapi
About the Author This book was prepared by Andrés Cruz Yoris, Bachelor of Computer Science, with more than 10 years of experience in the development of web applications in general; I work with PHP, Python and client side technologies like HTML, JavaScript, CSS, Vue among others and server side like Laravel, Flask , Django and CodeIgniter . I am also a developer in Android Studio, xCode and Flutter for the creation of native applications for Android and IOS. I put at your disposal part of my learning, reflected in each of the words that make up this book, my twelfth book on software development but the second focused on Python, for the development of web applications with FastApi.
Copyright No part of this book may be reproduced or transmitted in any way; that is, electronically or by photocopying without permission from the author.
Foreword FastAPI is a great web framework for creating web APIs with Python; It offers us multiple features with which it is possible to create modular, well-structured, scalable APIs with many options such as validations, formats, typing, among others. When you install FastAPI, two very important modules are installed: ● Pydantic that allows the creation of models for data validation. ● Starlette, which is a lightweight ASGI tooltip, used to create asynchronous (or synchronous) web services in Python. With these packages, we have the basics to create APIs, but we can easily extend a FastAPI project with other modules to provide the application with more features, such as the database, template engines, among others. FastAPI is a high-performance, easy-to-learn, start-up framework; It is ideal for creating all kinds of sites that not only consist of APIs, but we can install a template manager to return complete web pages. This book is mostly practical, we will learn the basics of FastAPI, knowing its main features based on a small application that we will expand chapter after chapter.
Who is this book for This book is aimed at anyone who wants to learn how to develop their first APIs in FastApi. For those people who know how to program in Python or other web frameworks. For those people who want to learn something new. For people who want to improve a skill and who want to grow as a developer and who want to continue scaling their path in application development with Python.
Considerations Remember that when you see the $ symbol it is to indicate commands in the terminal; you don't have to write this symbol in your terminal, it is a convention that helps to know that you are executing a command. At the end of each chapter, you have the link to the source code so you can compare it with your code. The use of bold in paragraphs has two functions: 1. If we put a letter in bold it is to highlight some code such as names of variables, tables or similar. 2. Highlight important parts or ideas. To display tips we use the following layout: important tips For the code snippets: from fastapi import ***, Query @app.get("/page") def page(page: int = Query(1, ge=1, le=20), size: int = Query(5, ge=5, le=20)): return {"page": page, "size": size} When using the *** It means that we are indicating that there are fragments in the code that we presented previously. As a recommendation, use Visual Studio Code as an editor, since it is an excellent editor, with many customization options, extensions, intuitive, lightweight, and that you can develop on a lot of platforms, technologies, frameworks , and programming languages; so all in all Visual Studio Code will be a great companion for you. https://code.visualstudio.com/ This book has a practical focus, therefore, we will be presenting the main components of FastApi, ranging from a hello world to more complex structures and thus have a clear approach to this technology. Remember that you can consult from the book's index, the different components in case you want to review a particular topic at any time.
Errata and comments If you have any questions, recommendations or found any errors, you can let them know at the following link: https://www.desarrollolibre.net/contacto/create By my email: desarrollolibre.net@gmail.com Or by Discord on the FastApi channel: https://discord.gg/sg85Zgwz96 As a recommendation, before reporting a possible problem, check the version you are referring to and add it in your comment; it is found on the second page of the book.
Introduction This guide is intended to get you started with FastAPI using Python; with this, we are going to raise two things: 1. It is not a book whose objective is to know FastApi 100%, or from zero to an expert, since it would be too big an objective for the scope of this guide, if not, to know what it offers us, to create the first methods that make up our API and how to customize them at the level of arguments, responses among others; in addition to learning how to integrate FastAPI with other third-party components. 2. It is assumed that the reader has at least basic knowledge of Python development. This book has a practical approach, knowing the key aspects of technology and going into practice, gradually implementing small features of an application that has a real scope. To follow this book you need to have a computer running Windows, Linux, or MacOS. The book is currently in development.
Map This book consists of 12 chapters, with which we will know in detail the most important and basic features of FastAPI: Chapter 1: We present some essential commands to develop in FastApi , we will prepare the environment and we will give an introduction to the framework . Chapter 2: One of the main factors in FastApi is the creation of resources for the API through functions, in this section we will deal with the basics of this, introducing routing between multiple files as well as the different options for the arguments and parameters of these routes. Chapter 3: In this section, learn how to handle HTTP status codes from API methods and also handle errors/exceptions from API methods. Chapter 4: In this section we will see how to create sample data to use from the automatic documentation that FastAPI offers for each of the API methods. Chapter 5: In this chapter we will see how to implement the upload of files, knowing the different existing variants in FastAPI. Chapter 6: In this chapter we will see how to connect a FastAPI application to a relational database such as MySQL. Chapter 7: In this chapter we will see installing and using a template engine in Python, specifically Jinja, with which we can return responses in HTML format. Chapter 8: In this chapter we will see installing and using a template engine in Python, specifically Jinja, with which we can return responses in HTML format. Chapter 9: In this chapter we will learn how to use dependencies. Chapter 10: In this chapter we will see how to use middleware to intercept requests to API methods and execute some procedure before the request or after generating the response. Chapter 11: In this chapter we will see how to create a user module, to register users, login, generate access tokens and logout. Chapter 12: In this chapter we will see how to implement unit tests.
Table of Contents Getting started with FastApi 1 Tweet about the book! 3 About the Author 4 Copyright 5 Chapter 1: Required software and tools installation 1 Required Software 1 Python 1 Visual Studio Code 2 Extension 2 Web browser 2 Chapter 2: Introduction to FastApi 3 Verify command access to Python 3 and Pip 3 Basic commands 4 Prepare the environment 4 Virtual environment 5 Install dependencies and prepare the project 5 FastApi 6 Uvicorn 6 Hello World 6 Parameters in routes (path) 8 Types of routes 9 FastApi core libraries 9 Chapter 3: Routing in FastApi 11 Routing between multiple files 11 Limit allowed values (predefined data) 17 Parameters with Query() 18 Path with Path() 19 Body 20 Validation of request bodies using Pydantic models 23 Validations 24 Nest classes 26 Inheritance 27 Validation by fields 28 Optional values and default values 29 Field types 32 Use a list as an argument 33 FastAPI automatic documentation 34 Swagger 34 ReDoc 34 Conclusions 35 Capítulo 4: Errors and status codes 36
HTTP status codes 36 Customize response status code in methods 36 Error handling 38 What is an HTTP exception? 38 Evaluate that the index is not out of range 39 Evaluate that the task has not been registered 39 Conclusion 40 Chapter 5: Declare sample data 41 Sample data in models 41 Nested relations 42 Option list 44 Sample data from argument 45 Sample data from argument 45 Simple example 45 Option list 46 Chapter 6: File Upload 47 File 47 UploadFile 48 Save file 49 Handle multiple files 50 Chapter 7: Database 51 Install dependencies 51 Configure connection 51 Changes in models 52 Create models (tables) of the database 52 Use the connection and create the tables in the database 53 Inject database session dependency in routes 55 What is the Depends class used for? 57 Demo: yield vs return 57 CRUD methods for tasks, database 58 Pagination 59 Relations 61 One to Many relationship 61 Changes in the CRUD of tasks (database) 62 Get the relationship from the main entity 63 Inverted relations 64 Many to Many relationship 65 Operations in a many-to-many relationship 67 Task CRUD changes (API methods) 68 Methods to add/remove tags to a task 68 Move sample data to separate files 69 API methods 72 Check if id exists in getById() 74 Integration of the SQLAlchemy and Pydantic classes in the response of the API methods 74 Reading and writing Pydantic models 75 Remove columns from queries in SQLAlchemy 77
Dates 78 Chapter 8: Template in FastAPI 79 About Jinja 79 First steps with Jinja 79 Control blocks 79 Conditionals 79 Bucle for 80 Filters 80 Filter default 80 Filter escape 81 Filter conversion 81 Filter max 81 Filter min 82 Filter round 82 Filter replace 82 Filter join 83 Filter lower 83 Filter upper 83 Filtro reverse 83 Filter length 84 Filter sort 84 Filter slice 85 Set variables 85 Blocks 85 Block raw 86 Block macro 86 Template inheritance 86 Master template 86 Include View Fragments 89 Using Jinja in FastAPI 89 Install Jinja 89 HTML task list 91 Requests in JavaScript 92 Create a task 92 Update a task 95 Delete a task 97 HTML forms 97 Chapter 9: Dependencies 102 Path dependencies (API method decorator) 103 Define dependencies as variables 103 Chapter 10: Introduction to Middleware 105 Create a middleware 105 Chapter 11: Authentication 107 Basic authentication 107 Database authentication 109 Methods for the API 112
Protect routes with authenticated user 114 Logout 115 Protecting API methods using the OAuth2PasswordBearer dependency 116 Verify access token at token creation time 117 Capítulo 12: Annotations, Ellipsis (...) notation, and return types 119 Ellipse notation 119 Annotated 120 Examples using Annotated 122 Return types 123 Chapter 13: Testing in FastAPI applications 124 pytest, for unit tests 124 Creating the first unit tests 124 Delete repetition with pytest fixtures 126 Extra: Loop event 128 Base configurations 132 Testing the user module 134 Create a user 134 Login 136 Logout 136 Testing the task module 137 Create a task (Body Json) 137 Update a task 138 Get all tasks 139 Get the detail of a task 139
Chapter 1: Required software and tools installation Python is an excellent language to start programming, it is simple, modular, and due to its very structure, when using indentation to delimit the structure, the code is correctly indented; with basic knowledge of Python, we can use it to master a large part of the framework as we are going to learn in this book. Required Software As fundamental software, we need Python, this is the only program that you have to install on your computer, since it is the programming language in which FastAPI is programmed, and the one that we have to use to create our applications with this framework; the python web has been this: https://www.python.org/ Python Before we go any further, let's talk a bit more about Python; Python is a high-level and interpreted programming language, object-oriented and with a very clean, friendly, easy-to-learn syntax and great readability with a large number of packages, modules, libraries and frameworks at our disposal make it very attractive for rapid application development. Programmers often fall in love with Python because of the increased productivity it provides. Since there is no build step, the edit, test, and debug cycle is incredibly fast and easy. There is no need for you to install a new version of Python since you can work with the one that already comes with your system. But, in case you need to install Python, it's extremely easy; we go to the official website, in the download section: https://www.python.org/ 1
We download it, execute it and it is the typical “next next next” to install it; very important that you add Python to the Windows PATH: Visual Studio Code As a code editor, we are going to use Visual Studio Code since it is an excellent editor, with many customization options, extensions, intuitive, light and that you can develop on a lot of platforms, technologies, frameworks and programming languages; so overall Visual Studio Code will be a great companion for you; but, if you prefer other editors like Sublime Text, or similar, you can use it without any problem. https://code.visualstudio.com/ Extension If you use VSC, you have to install the python extension: https://marketplace.visualstudio.com/items?itemName=ms-python.python Web browser As a web browser, I recommend Google Chrome; although it is true that when developing in web technologies, it is advisable to use more than one browser; by developing specifically for the server side and not focusing on developing on the client side; It doesn't make much sense for this book to use multiple browsers; that being said, you can use any other browser in case Google Chrome is not to your liking: https://www.google.com/intl/es/chrome/ 2
Chapter 2: Introduction to FastApi In this first chapter we are going to learn about some essential commands to be able to work on a project with FatApi, as well as preparing the development environment through virtual environments and creating the first example with FastApi, that is, "Hello World". Verify command access to Python 3 and Pip Before you start, it's important to check which version of Python you're using; in some operating systems such as Linux or MacOS an old version of Python may be installed, often version 2 of Python with which you cannot use FastApi; to be able to create our applications with FastApi it is necessary that you have version 3. Once Python 3 is installed on your computer, check what is the way to access it; in your terminal, if you run the following command: $ python -V And you see something like this: command not found: python It means that Python hasn't been installed, or at least it's not the way to access Python 3; if you see output like this: Python 3.X It means that to access the Python interpreter you have to simply type "python" in your terminal. In case the previous command did not work, you can try running the command of: $ python3 -V And you should see an output like: Python 3.X Where "X" is a variant of Python 3, such as 3.10.2 which means this is the way to access the Python interpreter on your PC. You must do the same procedure with the package installer for Python, the so-called pip: $ pip3 -V Or $ pip -V In at least one case you should see something like: 3
pip 22.X from /Library/Frameworks/ Python.framework /Versions/***/pip (python 3.X) Basic commands In order to create our applications in Python in an organized way, you should at least know the following commands, which are very useful at the time of development; let's see what they are. To install dependencies in Python, which can be from a plugin to perform the social login or a framework like Django, Flask or in this case FastApi, you must use the option "pip install" followed by the package or packages we want to install; for example: $ pip install fastapi To uninstall a package, we have the command "pip uninstall": $ pip uninstall fastapi Another very useful command is the one that allows us to know which packages we have installed in a project; as it happens with other environments like Node or PHP with Composer, in Python many times when the installed packages contain dependencies; for example, in the case of Django, when you install Django, the following dependencies are installed: $ pip install django asgiref ==3.5.0 django==4.0.3 sqlparse ==0.4.2 tzdata ==2021.5 To know the dependencies, we have the following command: $ pip freeze Whose output we can save in a file, which by convention is called as requirements.txt: $ pip freeze > requirements.txt We can now use this file to install the dependencies of a project with the exact versions; very useful when you are developing a python project with multiple people or when you go to production or simply when you need to run the project on multiple PCs: $ pip install -r requirements.txt Prepare the environment Having clarified some basic commands that we must know both to execute project files and to maintain the project and its dependencies, we are going to create the virtual environment to create the first application in FastApi. 4
Virtual environment In Python, virtual environments are development environments isolated from the operating system, therefore, the packages that we install will not be installed in the operating system but in the virtual environment; we can create as many virtual environments as we want, usually we have one virtual environment per project and with this, all the packages and dependencies necessary for a Python project in general are managed independently. In Python, virtual environments can be created and managed with the venv tool, which is included in the Python standard library, although it is also possible to install it using: $ pip install virtualenv This is the only package that needs to be installed at the global level of the operating system. To create the virtual environment, we have the command: $ python3 -m venv venv We are going to execute the following command: $ python3 -m venv vtasks Which will generate the virtual environment, which is nothing more than a folder with several files and folders; to activate it, from the virtual environment folder: $ cd vtasks We run on MacOS or Linux: $ source vtasks/bin/activate On Windows the command would be like: $ vtasks\Scripts\activate And with this, we already have everything ready to indicate our project; remember that to execute any Python or pip command you must always have the virtual environment active. Install dependencies and prepare the project For our first project, we are going to create a task app; to do this, inside the virtual environment folder, we will create the project folder that we will simply call tasks; leaving the project as follows: ● vtasks ○ include ○ lib ○ Scripts -- On Windows ○ bin -- On MacOS or Linux ○ pyvenv.cfg ○ tasks 5
Comments 0
Loading comments...
Reply to Comment
Edit Comment