{"id":2056,"date":"2024-01-23T08:40:03","date_gmt":"2024-01-23T08:40:03","guid":{"rendered":"https:\/\/blog.amt.in\/?p=2056"},"modified":"2024-01-23T08:40:03","modified_gmt":"2024-01-23T08:40:03","slug":"insights-on-fastapi","status":"publish","type":"post","link":"https:\/\/blog.amt.in\/index.php\/2024\/01\/23\/insights-on-fastapi\/","title":{"rendered":"Insights on FastAPI"},"content":{"rendered":"<p>FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It was created by Sebasti\u00c3\u00a1n Ram\u00c3\u00adrez and is designed to be easy to use, fast to develop with, and provide automatic validation of request and response data using Python&#8217;s type hints.<\/p>\n<p>Key features of FastAPI include:<\/p>\n<ol>\n<li><strong>Fast Execution:<\/strong> It is built on top of Starlette and Pydantic, making use of asynchronous programming for high performance.<\/li>\n<li><strong>Automatic Documentation:<\/strong> FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc based on the Python type hints provided in your code.<\/li>\n<li><strong>Type Annotations:<\/strong> FastAPI leverages Python type hints for request and response parameters, enabling automatic validation and generation of OpenAPI (formerly Swagger) documentation.<\/li>\n<li><strong>Dependency Injection:<\/strong> It supports dependency injection, making it easy to organize and manage dependencies in your application.<\/li>\n<li><strong>WebSocket Support:<\/strong> FastAPI includes support for WebSocket communication, allowing bidirectional communication between the client and server.<\/li>\n<li><strong>Security Features:<\/strong> It includes built-in security features, such as OAuth2 and API key authentication, as well as support for dependency injection for managing security requirements.<\/li>\n<\/ol>\n<p>Here&#8217;s a simple example of a FastAPI application:<\/p>\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\">\n<p><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fastapi <span class=\"hljs-keyword\">import<\/span> FastAPI<\/code><\/p>\n<p>app = FastAPI()<\/p>\n<p><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">&#8220;\/&#8221;<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_root<\/span>():<br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">&#8220;Hello&#8221;<\/span>: <span class=\"hljs-string\">&#8220;World&#8221;<\/span>}<\/p>\n<p><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">&#8220;\/items\/{item_id}&#8221;<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_item<\/span>(<span class=\"hljs-params\">item_id: <span class=\"hljs-built_in\">int<\/span>, query_param: <span class=\"hljs-built_in\">str<\/span> = <span class=\"hljs-literal\">None<\/span><\/span>):<br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">&#8220;item_id&#8221;<\/span>: item_id, <span class=\"hljs-string\">&#8220;query_param&#8221;<\/span>: query_param}<\/p>\n<\/div>\n<\/div>\n<p>In this example, the <code>read_root<\/code> function responds to the root endpoint (&#8220;\/&#8221;) with a JSON response, and the <code>read_item<\/code> function responds to the &#8220;\/items\/{item_id}&#8221; endpoint with the item_id and an optional query parameter.<\/p>\n<p>To run a FastAPI application, you typically use the <code>uvicorn<\/code> ASGI server:<\/p>\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">bash<\/div>\n<div class=\"p-4 overflow-y-auto\"><code class=\"!whitespace-pre hljs language-bash\">uvicorn your_app_name:app --reload<br \/>\n<\/code><\/div>\n<\/div>\n<p>Replace <code>your_app_name<\/code> with the actual name of your Python file or module containing the FastAPI app instance.<\/p>\n<p>FastAPI has gained popularity for its combination of speed, ease of use, and automatic documentation generation, making it a popular choice for building APIs with Python.<\/p>\n<p>Here are some more features and concepts in FastAPI:<\/p>\n<ol>\n<li><strong>Data Validation with Pydantic:<\/strong> FastAPI uses Pydantic models for data validation and serialization. By defining data models using Pydantic, you get automatic validation of request and response data based on the declared types.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\">\n<p><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> pydantic <span class=\"hljs-keyword\">import<\/span> BaseModel<\/code><\/p>\n<p><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title class_\">Item<\/span>(<span class=\"hljs-title class_ inherited__\">BaseModel<\/span>):<br \/>\nname: <span class=\"hljs-built_in\">str<\/span><br \/>\ndescription: <span class=\"hljs-built_in\">str<\/span> = <span class=\"hljs-literal\">None<\/span><br \/>\nprice: <span class=\"hljs-built_in\">float<\/span><br \/>\ntax: <span class=\"hljs-built_in\">float<\/span> = <span class=\"hljs-literal\">None<\/span><\/p>\n<\/div>\n<\/div>\n<\/li>\n<li><strong>Path Parameters and Query Parameters:<\/strong> FastAPI supports path parameters, query parameters, and request bodies, allowing you to easily define and handle different types of data in your API.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\"><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">\"\/items\/{item_id}\"<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_item<\/span>(<span class=\"hljs-params\">item_id: <span class=\"hljs-built_in\">int<\/span>, query_param: <span class=\"hljs-built_in\">str<\/span> = <span class=\"hljs-literal\">None<\/span><\/span>):<br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">\"item_id\"<\/span>: item_id, <span class=\"hljs-string\">\"query_param\"<\/span>: query_param}<br \/>\n<\/code><\/div>\n<\/div>\n<\/li>\n<li><strong>Request and Response Objects:<\/strong> FastAPI provides <code>Request<\/code> and <code>Response<\/code> objects that you can use to access information about the incoming request and customize the outgoing response.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\">\n<p><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fastapi <span class=\"hljs-keyword\">import<\/span> Request<\/code><\/p>\n<p><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">&#8220;\/headers&#8221;<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_headers<\/span>(<span class=\"hljs-params\">request: Request<\/span>):<br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">&#8220;headers&#8221;<\/span>: request.headers}<\/p>\n<\/div>\n<\/div>\n<\/li>\n<li><strong>Dependency Injection:<\/strong> FastAPI has a built-in dependency injection system that allows you to organize and manage dependencies in your application. Dependencies can be automatically injected into route functions.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\">\n<p><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fastapi <span class=\"hljs-keyword\">import<\/span> Depends, HTTPException<\/code><\/p>\n<p><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">get_current_user<\/span>(<span class=\"hljs-params\">api_key: <span class=\"hljs-built_in\">str<\/span> = Depends(get_api_key)<\/span>):<br \/>\n<span class=\"hljs-comment\"># Dependency logic here<\/span><br \/>\n<span class=\"hljs-keyword\">return<\/span> User(api_key)<\/p>\n<p><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">&#8220;\/users\/me&#8221;<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_current_user<\/span>(<span class=\"hljs-params\">current_user: User = Depends(get_current_user)<\/span>):<br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">&#8220;username&#8221;<\/span>: current_user.username}<\/p>\n<\/div>\n<\/div>\n<\/li>\n<li><strong>Security and Authentication:<\/strong> FastAPI includes built-in support for OAuth2, API key authentication, and other security features. You can easily add authentication and authorization to your routes.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\"><code class=\"!whitespace-pre hljs language-python\"><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fastapi <span class=\"hljs-keyword\">import<\/span> Depends, HTTPException, status<br \/>\n<span class=\"hljs-keyword\">from<\/span> fastapi.security <span class=\"hljs-keyword\">import<\/span> OAuth2PasswordBearer<\/code><\/code>security = OAuth2PasswordBearer(tokenUrl=<span class=\"hljs-string\">&#8220;token&#8221;<\/span>)<\/p>\n<p><code class=\"!whitespace-pre hljs language-python\"><code class=\"!whitespace-pre hljs language-python\"><\/code><\/code><span class=\"hljs-meta\">@app.get(<span class=\"hljs-params\"><span class=\"hljs-string\">&#8220;\/users\/me&#8221;<\/span><\/span>)<\/span><br \/>\n<span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title function_\">read_current_user<\/span>(<span class=\"hljs-params\">token: <span class=\"hljs-built_in\">str<\/span> = Depends(security)<\/span>):<br \/>\n<span class=\"hljs-comment\"># Verify token logic here<\/span><br \/>\n<span class=\"hljs-keyword\">return<\/span> {<span class=\"hljs-string\">&#8220;token&#8221;<\/span>: token}<\/p>\n<\/div>\n<\/div>\n<\/li>\n<li><strong>Middleware Support:<\/strong> FastAPI supports the use of middleware to customize the behavior of your application. You can add middleware functions to handle tasks such as logging, authentication, or other pre-processing.\n<div class=\"bg-black rounded-md\">\n<div class=\"flex items-center relative text-gray-200 bg-gray-800 dark:bg-token-surface-primary px-4 py-2 text-xs font-sans justify-between rounded-t-md\">python<\/div>\n<div class=\"p-4 overflow-y-auto\">\n<p><code class=\"!whitespace-pre hljs language-python\"><span class=\"hljs-keyword\">from<\/span> fastapi.middleware.cors <span class=\"hljs-keyword\">import<\/span> CORSMiddleware<\/code><\/p>\n<p>app.add_middleware(<br \/>\nCORSMiddleware,<br \/>\nallow_origins=[<span class=\"hljs-string\">&#8220;*&#8221;<\/span>],<br \/>\nallow_credentials=<span class=\"hljs-literal\">True<\/span>,<br \/>\nallow_methods=[<span class=\"hljs-string\">&#8220;*&#8221;<\/span>],<br \/>\nallow_headers=[<span class=\"hljs-string\">&#8220;*&#8221;<\/span>],<br \/>\n)<\/p>\n<\/div>\n<\/div>\n<\/li>\n<\/ol>\n<p>These are just a few of the many features and capabilities of FastAPI. The framework is designed to be powerful, efficient, and easy to use, making it a great choice for building APIs in Python.<\/p>\n<p>Above is the brief about FastAPI. Watch this space more updates on the latest trends in Technology<\/p>\n","protected":false},"excerpt":{"rendered":"<p>FastAPI is a modern, fast<\/p>\n","protected":false},"author":1,"featured_media":2058,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[547,1075,153,7],"tags":[548,1076,155,18],"class_list":["post-2056","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-api","category-fastapi","category-python","category-techtrends","tag-api","tag-fastapi","tag-python","tag-technology"],"_links":{"self":[{"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/posts\/2056","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/comments?post=2056"}],"version-history":[{"count":2,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/posts\/2056\/revisions"}],"predecessor-version":[{"id":2059,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/posts\/2056\/revisions\/2059"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/media\/2058"}],"wp:attachment":[{"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/media?parent=2056"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/categories?post=2056"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.amt.in\/index.php\/wp-json\/wp\/v2\/tags?post=2056"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}