Terraform: The Powerful Tool of DevOps
January 23, 2024Best Practices In Flutter Mobile Development
February 26, 2024FastAPI is described as a modern and high-performance web framework for developing APIs with Python 3.7+.
True to its name, FastAPI is fast. It offers high performance on par with NodeJS and GO. It is used by top companies like Uber and Netflix to build their applications.
What is API ?
API is the mediator between our database and system of application or website.
Function :
To take request from browser through internet and pass to database through server and give the response back again.
What is ASGI (Asynchronous Server Gateway Interface) and WSGI ( Web Server Gateway Interface ) ?
As we already discussed, FastAPI works on ASGI while Flask works on WSGI.
- WSGI handles requests synchronously. When requests come in, they are processed to finish doing their tasks sequentially or one after the other. They have to wait until the one before it finishes before switching to a new task.
- ASGI(Asynchronous Server Gateway Interface) is the spiritual successor of WSGI. It processes requests asynchronously, in the opposite way of WSGI.
- When requests are processed asynchronously, the beauty is that they don’t have to wait for the others before them to finish doing their tasks. The different requests can do their processing finishing in no particular order.
What is Data Validation ?
- FastAPI provides document validation functionality that ensures that the data you receive in your API endpoints conforms to a specified schema. Document validation is a critical component of building robust and secure web applications because it protects against malicious or poorly-formed requests that could cause unexpected behavior or security issues.
- FastAPI leverages Pydantic, a data validation library, to implement document validation. Pydantic enables you to define your data model and its constraints as Python classes. It uses type annotations to declare the expected types for each attribute and provides a range of validation methods to enforce constraints on those types.
- Commands to perform in CLI :
(i) pip install pydantic
(ii) From pydantic import Basemodel
(iii) After that create a class by giving classname (:here bank:) and define column name with its datatype which means that age, duration,campaign ,etc. value should only allow integer data type value as a user input while emp_var_rate should allow float data type.
(iv) Next when you are creating api, give data validation by giving class name as
an argument inside a user defined function.Make sure that both the variables the columns are the same.
What is Documentation ?
- The .docs feature provides an interactive interface that allows you to test and interact with your API directly from the documentation. You can enter parameters and payloads, send requests, and see the responses in real-time.
- FastAPI’s .docs feature also supports various customization options, such as adding descriptions, examples, and custom headers for your endpoints. This allows you to provide additional information and context for your API users, making it easier for them to understand and use your API.
- Overall, the .docs feature in FastAPI is a powerful tool that helps developers build and document APIs quickly and easily, while also providing a user-friendly interface for API consumers to explore and interact with the API.
- Index , Get Name , predict are different apis created which can be seen here
By using the downside arrow and Try It Out tab you can pass input and run the functionalities as well as see the output by clicking on the Execute function.
As well can see response code of error and success.
If code faces any error it can also show the error like
Flask VS FastAPI
No. | Flask | Fast API |
1. | Works on WSGIn | Works on ASGI |
2. | Need to do data validation manually | In-built feature of data validation |
3. | http methods:@app.route(“/”, methods = [“GET”]) | http methods:@app.get(“/”) |
4. | Does not support asynchronous task | Supports asynchronous task |
5. | Need to make documentation manually | Automatic document support |
6. | Larger community support | Smaller community support |
7. | Comparingly less easy | Easy and faster |
8. | Error messages are displayed in html format | Error messages are displayed in clear format of json |
What is Uvicorn in FastAPI?
Uvicorn is a lightning-fast ASGI (Asynchronous Server Gateway Interface) server that is used by FastAPI to run web applications.
Uvicorn is designed to take advantage of Python’s asyncio library to handle multiple connections asynchronously and efficiently, making it an excellent choice for high-performance web applications.
How do I open up adopting FastAPI?
- Install and import fastapi library :
- pip install fastapi
- from fastapi import FastAPI
- Create instance and define route :
Create a new instance of the FastAPI class and define a new route with the @app.get decorator.
- app = FastAPI() (to create new instance of the FastAPI class)
( Here : The @app.get decorator maps the /hello URL endpoint to the hello() function.)
- Define function
Define a new asynchronous function, which returns the output when the route is requested. The async keyword indicates that the function is asynchronous, which means that it can run concurrently with other functions and I/O operations.
- To take user input
If you want to take user input you can go for by specifying variable into curly brackets {}.
If a user tries to access the endpoint without a name parameter or with an invalid name value, FastAPI will return a JSON response with a 422 Unprocessable Entity status code and an error message indicating the validation error.
- Data Validation
- Code has been declared to give user input which will be stored in the name variable.
- While defining and using that variable, we can use a data validation facility if that variable is needed to pass a specific data type.
- When the route is requested, FastAPI will extract the value of the name parameter from the URL path and pass it as an argument to the welcome() function.
- FastAPI will automatically validate the input data against the Name model and raise an HTTP exception if the data is invalid.
(Here : Code has declared variable “name” which is user input and should be of string data type only)
- How to run the fastapi code ?
- Open new terminal
- Go to your folder or project by using cd project_name or cd folder_name
- Run below command line :
uvicorn file_name.py:fast_api instance name –reload
(Here : we have created instance of FastAPI in object called app and our file_name is credit_fastapi.py)
- –reload option is used to enable automatic code reloading. When you include –reload as a command-line argument when starting the server, Uvicorn will monitor your application’s source code files for changes. If any changes are detected, Uvicorn will automatically restart the server, ensuring that the updated code is loaded and the changes take effect.
- Using the –reload option during development is beneficial because it allows you to make changes to your FastAPI application without manually stopping and restarting the server after each code modification. This helps to streamline the development process by providing a quicker feedback loop and saving you the hassle of manual server restarts.
How should the global community expand by employing FASTAPI?
- Real-time data processing
FastAPI’s asynchronous capabilities enable real-time data processing and analysis. It can be used to build applications that can process and analyze data streams in real-time, enabling organizations to make faster decisions and respond to events more quickly.
- Machine learning
FastAPI’s support for Python’s type hints and easy integration with popular machine learning libraries, such as TensorFlow and PyTorch, make it an ideal choice for building machine learning-based applications. These applications can be used for a wide range of use cases, such as predictive analytics, natural language processing, and computer vision.
- Cloud-native applications
FastAPI’s support for Docker and Kubernetes make it easy to build cloud-native applications that can run on any cloud provider or on-premises infrastructure. This enables organizations to build scalable and resilient applications that can adapt to changing business needs.
In conclusion, FastAPI can be used efficiently in digital transformation by enabling the creation of APIs, microservices-based applications, real-time data processing, machine learning-based applications, and cloud-native applications. Its high performance, scalability, and ease of use make it an excellent choice for modern digital transformation projects.
For more reference : https://fastapi.tiangolo.com/