Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
FastAPIis a modern, high-performance web framework for building APIs with Python. It is designed to be easy to use and learn while providing powerful features like automatic validation, serialization, and automatic interactive API documentation. Additionally, it works with any template engine and allows you to use any default template configuration needed for your project.
Let’s dive into the details of FastAPI, its features, and how to use it effectively. Later in this article, we will also look into IronPDF a PDF generation Python package from Iron Software.
You can install FastAPI and Uvicorn (an ASGI server) using pip:
pip install fastapi
pip install "uvicorn[standard]"
pip install fastapi
pip install "uvicorn[standard]"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastapi pip install "uvicorn[standard]"
Here’s a simple example to get you started with FastAPI and expose Python data through a user interface:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
from fastapi import FastAPI app = FastAPI() app.get("/") def read_root(): Return
If True Then
"Hello": "World"
End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@app.@get("/items/{item_id}") # @with query parameters def read_item(item_id: int, q: str = None): Return
'{
''INSTANT VB TODO TASK: The following line uses invalid syntax:
'' "item_id": item_id, "q": q}
To run the application, use Uvicorn:
uvicorn main:app --reload
uvicorn main:app --reload
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'uvicorn main:app --reload
This command will start a development server and automatically reload for code changes. You can access the interactive API documentation at http://127.0.0.1:8000/docs
.
FastAPI supports a wide range of advanced features, making it suitable for complex applications:
Let’s build a simple CRUD (Create, Read, Update, Delete) API for managing items.
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'from pydantic import BaseModel class Item(BaseModel): name: str description: str = None price: float tax: float = None
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {}
@app.post("/items/")
def create_item(item: Item):
item_id = len(items) + 1
items[item_id] = item
return item
@app.get("/items/{item_id}") # optional str query parameter
def read_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
@app.put("/items/{item_id}") # with path parameters
def update_item(item_id: int, item: Item):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
del items[item_id]
return {"message": "Item deleted"}
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {}
@app.post("/items/")
def create_item(item: Item):
item_id = len(items) + 1
items[item_id] = item
return item
@app.get("/items/{item_id}") # optional str query parameter
def read_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
@app.put("/items/{item_id}") # with path parameters
def update_item(item_id: int, item: Item):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
del items[item_id]
return {"message": "Item deleted"}
404, detail="Item not found"
status_code=404, detail
404, detail="Item not found"
status_code=404, detail
404, detail="Item not found"
status_code=404, detail
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id] = item return item @app.get("/items/{item_id}") # optional str query parameter def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return items[item_id] @app.put("/items/{item_id}") # with path parameters def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") items[item_id] = item return item @app.delete("/items/{item_id}") def delete_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") del items[item_id] return
item Return item app.get("/items/{item_id}") # [optional] str query parameter def read_item(item_id:= Integer): if item_id [not] in items: raise HTTPException(status_code) Return items(item_id) app.put("/items/{item_id}") # [with] path parameters def update_item(item_id: Integer, item: Item): if item_id [not] in items: raise HTTPException(status_code) items(item_id) = item Return item app.delete("/items/{item_id}") def delete_item(item_id: Integer): if item_id [not] in items: raise HTTPException(status_code) del items(item_id) Return
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id] = item return item @app.get("/items/{item_id}") # optional str query parameter def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code) return items[item_id] @app.put("/items/{item_id}") # with path parameters def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code) items[item_id]
len(items) + 1 items(item_id) = item Return item app.get("/items/{item_id}") # [optional] str query parameter def read_item(item_id:= Integer): if item_id [not] in items: raise HTTPException(status_code) Return items(item_id) app.put("/items/{item_id}") # [with] path parameters def update_item(item_id: Integer, item: Item): if item_id [not] in items: raise HTTPException(status_code) items(item_id)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id = len(items) + 1 items[item_id]
{} app.post("/items/") def create_item(item:= Item): item_id = len(items) + 1 items(item_id)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI, HTTPException app = FastAPI() items = {} @app.post("/items/") def create_item(item: Item): item_id
FastAPI() items = {} app.post("/items/") def create_item(item:= Item): item_id
from fastapi import FastAPI, HTTPException app = FastAPI() items
'INSTANT VB TODO TASK: The following line uses invalid syntax:
' "message": "Item deleted"}
IronPDF is a powerful Python library designed for creating, editing, and signing PDFs from HTML, CSS, images, and JavaScript. It offers commercial-grade performance with a low memory footprint. Key features include:
Convert HTML files, HTML strings, and URLs to PDFs. For example, render a webpage as a PDF using the Chrome PDF renderer.
Compatible with various .NET platforms, including .NET Core, .NET Standard, and .NET Framework. It supports Windows, Linux, and macOS.
Set properties, add security with passwords and permissions, and apply digital signatures to your PDFs.
Customize PDFs with headers, footers, page numbers, and adjustable margins. Supports responsive layouts and custom paper sizes.
Adheres to PDF standards such as PDF/A and PDF/UA. Supports UTF-8 character encoding and handles assets like images, CSS, and fonts.
pip install fastapi
pip install ironPDF
pip install fastapi
pip install ironPDF
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastapi pip install ironPDF
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "IronPDF"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.get("/pdf")
async def get_pdf(greet1: str = None,greet2: str = None):
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
content = "<h1>Document Generated using IronPDF with fastapi GET</h1>"
content += "<p> Demonstrate PDF generation using User Inputs"+"</p>"
content += "<p>"+f"Greetings from: {greet1}"+"</p>"
content += "<p>"+f"And Greetings from: {greet2}"+"</p>"
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("fastapi.pdf")
# To view the file in the browser, use "inline" for the media_type
headers = {
"Content-Disposition": "inline; filename=sample.pdf"
}
# Create a FileResponse object with the file path, media type and headers
response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
# Return the FileResponse object
return response
from fastapi import FastAPI
from fastapi.responses import FileResponse
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "IronPDF"}
@app.get("/items/{item_id}") # with query parameters
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
@app.get("/pdf")
async def get_pdf(greet1: str = None,greet2: str = None):
renderer = ChromePdfRenderer()
# Create a PDF from a HTML string using Python
content = "<h1>Document Generated using IronPDF with fastapi GET</h1>"
content += "<p> Demonstrate PDF generation using User Inputs"+"</p>"
content += "<p>"+f"Greetings from: {greet1}"+"</p>"
content += "<p>"+f"And Greetings from: {greet2}"+"</p>"
pdf = renderer.RenderHtmlAsPdf(content)
# Export to a file or Stream
pdf.SaveAs("fastapi.pdf")
# To view the file in the browser, use "inline" for the media_type
headers = {
"Content-Disposition": "inline; filename=sample.pdf"
}
# Create a FileResponse object with the file path, media type and headers
response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers)
# Return the FileResponse object
return response
#Apply your license key
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: from fastapi import FastAPI from fastapi.responses import FileResponse from ironpdf import * License.LicenseKey = "key" app = FastAPI() @app.get("/") def read_root(): return
"key" app = FastAPI() app.get("/") def read_root(): Return
If True Then
From fastapi import FastAPI From fastapi.responses import FileResponse From ironpdf import * License.LicenseKey = "key" app
"Hello": "IronPDF"
End If
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@app.@get("/items/{item_id}") # @with query parameters def read_item(item_id: int, q: str = None): Return
'{
' "item_id": item_id, "q": q
'}
#Create a PDF from a HTML string using Python
#Export to a file or Stream
#To view the file in the browser, use "inline" for the media_type
#Create a FileResponse object with the file path, media type and headers
#Return the FileResponse object
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'@app.@get("/pdf") async def get_pdf(greet1: str = None,greet2: str = None): renderer = ChromePdfRenderer() content = "<h1>Document Generated using IronPDF with fastapi GET</h1>" content += "<p> Demonstrate PDF generation using User Inputs"+"</p>" content += "<p>"+f"Greetings from: {greet1}"+"</p>" content += "<p>"+f"And Greetings from: {greet2}"+"</p>" pdf = renderer.RenderHtmlAsPdf(content) pdf.SaveAs("fastapi.pdf") headers = { "Content-Disposition": "inline; filename=sample.pdf" } response = FileResponse("fastapi.pdf", media_type="application/pdf", headers=headers) Return response
This code snippet demonstrates the integration of IronPDF with FastAPI to dynamically generate PDF documents based on user inputs and serve them as a downloadable response.
Setting License Key: Applies the IronPDF license key to enable its features.
FastAPI Initialization: Initializes a FastAPI instance (`app`) to handle HTTP requests.3. Basic Route Handlers: `read_root()`: Responds with a simple JSON message indicating "Hello IronPDF" when accessing the root URL (`/`). `read_item()`: Accepts an `item_id` path parameter and an optional `q` query parameter. Returns a JSON response with these function parameters.
This code snippet illustrates how IronPDF can be seamlessly integrated with FastAPI to dynamically generate and serve PDF documents based on user inputs. It showcases the ability to convert HTML content into PDFs, making it suitable for applications requiring on-the-fly document generation and delivery over HTTP.
Below shows the swagger output generated from the APIs
IronPDF runs on the license key for python. IronPDF for Python offers a free trial license key to allow users to check out features before purchase.
Place the License Key at the start of the script before using the IronPDF package:
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
from ironpdf import *
# Apply your license key
License.LicenseKey = "key"
IRON VB CONVERTER ERROR developers@ironsoftware.com
FastAPI is a powerful and easy-to-use framework for building APIs in Python. FastAPI has high performance, automatic documentation, and advanced features make it an excellent choice for both beginners and experienced developers. Whether you’re building a simple API or a complex web application, FastAPI provides the tools you need to succeed.
IronPDF is a robust Python library for creating, manipulating, and rendering PDF documents from HTML content. It offers features like HTML to PDF conversion, interactive form creation, PDF manipulation (merging, splitting), and text extraction. Ideal for generating dynamic PDFs with ease and integrating into various Python applications.
9 .NET API products for your office documents