0% found this document useful (0 votes)
39 views

Unit-3 Deployment using FastAPI

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Unit-3 Deployment using FastAPI

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Deployment using FastAPI

Trainer: Ms. Nidhi Grover Raheja


Introducing FastAPI
• FastAPI is a modern web framework used to build APIs in Python
quickly and efficiently.
• It’s perfect for deploying machine learning models due to its
simplicity, speed, and automatic generation of interactive
documentation using OpenAPI and JSON Schema.
• FastAPI is a state-of-the-art Python web system made to make it more
straightforward to make superior execution APIs.
• FastAPI is a strong tool for creating reliable APIs with little code since
it makes use of Python 3.7+ capabilities, such as type annotations.
Characteristics of FastAPI
FastAPI is a leading option for API development because of several outstanding features,
including:
1. Automatic Documentation: Based on the type hints and docstrings in your code,
FastAPI automatically creates interactive documentation for your API using programs
like Swagger UI and ReDoc.
2. Type Hinting: Built-in Python type hints support guarantees reliable auto-completion
and validation in contemporary IDEs, enhancing code dependability.
3. Fast Performance: One of the quickest Python web frameworks available, FastAPI is
built for speed. It takes advantage of nonconcurrent programming to successfully deal
with different solicitations immediately.
4. Easy Validation: Request and input data are automatically verified, which reduces the
likelihood of errors. A selection of validation techniques is offered by FastAPI to
guarantee data consistency.
5. Authentication and Authorization: FastAPI supports OAuth2, JWT, and other
protocols, making it simple to implement authentication and authorization processes.
Advantages of FastAPI
• High Performance: FastAPI offers remarkable performance
thanks to its asynchronous features and effective request
management.
• Automatic Documentation: The documentation is generated
automatically, which reduces development time and
increases API comprehension.
• Pythonic: FastAPI's syntax and methodology are
understandable to developers who are familiar with Python.
• Type Safety: Type hinting makes code more readable and
lowers the risk of runtime problems.
Disadvantages of FastAPI
• Learning must: While FastAPI is user-friendly for beginners,
grasping its advanced features could necessitate some
learning.
• Young Ecosystem: FastAPI's ecosystem is still developing in
comparison to more established frameworks like Django.
• Limited Project Templates: Compared to certain other
frameworks, FastAPI provides fewer project templates and
conventions.
• Installation: To start using FastAPI, you need to install it along
with uvicorn, a server that runs FastAPI apps.

Let’s create it and activate

python3 -m venv venv


source venv/bin/activate

Install the necessary packages

pip install uvicorn fastapi joblib


Basic Structure of FastAPI application:

Here's an example of a simple FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
return {"message": "Hello, World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
Code Explanation
• FastAPI Initialization: The line app = FastAPI() creates a FastAPI instance. This
instance will handle all the incoming requests and routing.
• GET Request for Root URL:
✓@app.get("/"): This is a decorator that maps the root URL (/) to the
read_root() function.
✓When users visit the root URL (http://127.0.0.1:8000), the function returns
{"message": "Hello World"}.
• Dynamic Path Parameter:
• @app.get("/items/{item_id}"): The part {item_id} allows you to define a
dynamic URL segment.
• The function read_item() takes item_id as an integer parameter and an
optional query string q (e.g., ?q=something).
• The URL http://127.0.0.1:8000/items/42?q=test would return {"item_id": 42,
"query": "test"}.
Visit the Application in a Browser
Running the FastAPI instance:

• Make sure you are running the correct file and the correct app instance.
• If you have named your file main.py, the app should be referenced as main:app
when running uvicorn.
• For example, if your file is named main.py and your FastAPI instance is named
app, the command should be:

uvicorn name_of_app:app --reload


• Suppose we named the file as Fastapidemo.py so the command to run app
instance will be:

uvicorn Fastapidemo:app --reload


Click Here to see the output !!
Testing the Dynamic Route
Visit the URL http://127.0.0.1:8000/items/42?q=test
in your browser. You will see the response:
URL Breakdown
Step 4: Auto-Generated API Documentation
• FastAPI automatically generates API documentation based on
your code, which can be very useful for testing and exploring.
1. Open Swagger UI
➢Swagger UI: FastAPI automatically generates this documentation at
/docs.
➢Go to http://127.0.0.1:8000/docs.
➢Here, you can see the interactive API documentation, test your
endpoints, and view responses.
2. Open ReDoc
❖ReDoc: Another style of auto-generated documentation is available at
/redoc.
❖Go to http://127.0.0.1:8000/redoc to see a different view of the API
documentation.
Swagger UI → http://127.0.0.1:8000/docs
ReDoc → http://127.0.0.1:8000/redoc
GET and POST in Fast API
Handling POST Requests
• Let’s extend the FastAPI application by adding a POST request.
• POST requests are typically used to send data from the client to the
server.
• Modify the app.py: Modify your app.py file to include a POST route:
Test the POST Request
You can test the POST request using Postman
Feature GET POST
HTTP Method GET POST
Purpose Retrieve data from the server Send data to the server
Request Body Not allowed in GET requests Allowed (usually in JSON format)
Typically passed as query parameters or Passed in the request body (JSON, form-data,
Parameters
path variables etc.)

Yes (making the same request multiple No (multiple requests may cause different
Idempotency
times results in the same response) outcomes, e.g., multiple resource creation)

Can have side effects, like creating or


Side Effects No side effects, read-only
modifying resources
FastAPI Decorator @app.get("/path/") @app.post("/path/")
Fetching an item’s details, retrieving lists
Example Usage Creating a new item, submitting form data
of resources
Response Codes 200 (OK) 201 (Created), 200 (OK)
Caching Typically cacheable Typically not cacheable
Fetch data like product information, Create a new resource, submit a form, or
Common Use Cases
retrieve a user’s profile update a resource
Using Get and Post Together
• We can use both GET and POST together in FastAPI when you need to
provide different functionalities on the same or similar endpoints.
• For instance, you could have a GET request to retrieve a list of items
and a POST request to create a new item.
• This is quite common when working with RESTful APIs.
• Here's a full example where both GET and POST are used together:
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Pydantic model to define the structure of the item


class Item(BaseModel):
name: str
price: float
is_offer: bool = None

# Store items in memory for the example


items_db = []
# GET method to retrieve the list of all items
@app.get("/items/")
def read_items():
return {"items": items_db}

# GET method to retrieve a specific item by ID


@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < len(items_db):
return {"item": items_db[item_id]}
else:
return {"error": "Item not found"}
# POST method to create a new item
@app.post("/items/")
def create_item(item: Item):
items_db.append(item)
return {"message": "Item created", "item": item}
GET Request: Fetch All Items (/items/):
• Retrieves all items currently stored in items_db.
• This is useful for retrieving a list of resources.
• Example URL to test in Postman or browser:
http://127.0.0.1:8000/items/.
GET Request: Fetch Specific Item by ID
(/items/{item_id}):
• Retrieves an item from items_db by its index (ID).
• If the item ID does not exist, it returns an error message.
• Example URL to test in Postman or browser:
http://127.0.0.1:8000/items/0 (for the first item).
POST Request: Create a New Item (/items/):
• Allows users to send a POST request with a JSON payload to create a
new item.
• The item is added to the in-memory items_db list.
• Example payload (in Postman under the Body section):
How to Test the Example:
1. Start your FastAPI app by running this command:
uvicorn app:app –reload
2. Test the GET requests:
• In your browser or Postman, make a GET request to:
Retrieve all items: http://127.0.0.1:8000/items/
• Retrieve a specific item: http://127.0.0.1:8000/items/0
(replace 0 with the desired item ID)
3. Test the POST request:
• Open Postman and set the request type to POST.
• Use this URL: http://127.0.0.1:8000/items/
• In the Body tab, select raw and set the format to JSON

You might also like