How to create a simple GET request using FastAPI
In modern web development, building RESTful APIs is a very common task. FastAPI is a modern, fast (high-performance) web framework based on Python that provides a concise, easy-to-use way to build efficient APIs.
This article will introduce how to use the FastAPI framework to create a simple GET request. We will use FastAPI's decorator to route requests and write some simple handler functions to handle GET requests and return some data.
Step 1: Install FastAPI
First, we need to install FastAPI and uvicorn (for running ASGI applications).
FastAPI and uvicorn can be installed using the following command:
pip install fastapi uvicorn
Step 2: Create a basic FastAPI application
We will create a basic FastAPI application in the file program. Suppose we create a file called app.py and paste the following code into the file:
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"}
In the above code, we import FastAPI and instantiate a FastAPI application. Then, we define a root route /
using the @app.get
decorator. In the handler function read_root
, we simply return a dictionary containing {"Hello": "World"}
.
Step 3: Run FastAPI application
To run FastAPI application, we can use uvicorn server.
Open a terminal, go to the directory containing the app.py file, and run the following command:
uvicorn app:app --reload
In the above command, app refers to the name of the app.py file (without the file extension name). The --reload option is used to automatically reload the server when code changes.
Step 4: Test GET Request
Now we can use any HTTP client tool (such as a browser or Postman) to make a GET request to our API.
Open your browser and enter http://localhost:8000/, you should see the following response:
{ "Hello": "World" }
Done! We have successfully created a simple FastAPI application and returned some data using a GET request.
Conclusion
FastAPI is an excellent web framework that can help us quickly build efficient APIs. By using decorators to route requests, and writing simple handler functions, we can easily create endpoints that handle GET requests.
I hope this article can help you get started with FastAPI and provide you with some guidance for building a powerful API. I wish you success in your web development journey!
The above is the detailed content of How to create a simple GET request using FastAPI. For more information, please follow other related articles on the PHP Chinese website!